Given an arbitrary object:
class Val(object):
def __init__(self):
this_val = 123
I want to create an abstract base class which has an attribute that is a Val():
class A(object):
foo = Val()
I would expect that when my children inherit from that class, they would get copies of Val(). For example:
class B(A):
pass
class C(A):
pass
I would expect the following behavior:
>>> b = B()
>>> c = C()
>>> c.foo.this_val = 456
>>> b.foo.this_val
123
But instead I get:
>>> b.this_val
456
I understand that I could just self.foo = Val() into the init to achieve that behavior, but I have a requirement that foo remain an attribute (it is a model manager in django). Can anyone suggest a work around for this?
EDIT: I really need to be able to access the value as a class attribute, so my desired behavior is:
>>> C.foo.this_val = 456
>>> B.foo.this_val
123
Maybe using a descriptor would suit your requirements:
Now, as long as you make sure you don’t set the instance attribute “foo” of any of your objects, they will have a class attribute that is individual to each subclass:
EDIT: With the edit I made some hours ago, changing the key in
__get__to beobjtypeinstead ofobj.__class__, this also works when accessing the class attributes directly: