I have the following code:
class X(object):
items = []
class Y(X):
pass
class Z(X):
pass
I'm trying to create a decorator that will add an object only to Y's "item" list. So the following code,
@addItems
class Y(X):
pass
should append something (for sake of example, let's say the integer 1) to Y.items but not modify X.items, Z.items, or any other subclasses of X. Basically, Y.items should have items = [1] but X.items and Z.items should both have items = []. This is the decorator function definition I created that was supposed to achieve that goal:
def addItems(cls):
cls.items.append(1)
return cls
This does not work though - when I use the decorator, it ends up modifying the "items" list for X and all other subclasses of X. What gives? I know that class attributes in Python are shared among all instances of X, however, I did not know that subclasses were affected. Perhaps this behavior occurs only for mutable attributes?
What is the correct way of achieving my goal?
itemsattribute it searches the superclass and finds X's. What are you trying to achieve, overall?