Home > database >  should inheritance work for static variable
should inheritance work for static variable

Time:09-18

I'm not sure this is right question to be asked, may be inheritance works in instances only.

I have provided the code below where we are counting the how many X instances is been created using python descriptor based approach, where X is modifying the inherited static variable.

class X:
    def __set_name__(self, owner, name):
        owner.howManyX.append(name)


class Base:
    howManyX = []


class A(Base):
    a1 = X()
    a2 = X()
        

class B(Base):
    b1 = X()
    b2 = X()


print(id(A.howManyX), A.howManyX )
print(id(B.howManyX), B.howManyX)
print(id(Base.howManyX), Base.howManyX)

Since both A and B class should have inherited Base class howManyX. But output is bit unexpected as show below variable seem to be same.

139852096097856 ['a1', 'a2', 'b1', 'b2']
139852096097856 ['a1', 'a2', 'b1', 'b2']
139852096097856 ['a1', 'a2', 'b1', 'b2']

CodePudding user response:

This is inheritance. A and B are inheriting the same attribute from Base and mutating the object it refers to.

You want the opposite of inheritance, you want to override howManyX = [] in each of the subclasses, so each class gets it's own attribute referring to a distinct object.

Notice, you get the exact same behavior using an instance:

>>> class Foo:
...     bar = []
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.bar.append('baz')
>>> foo2.bar.append('bing')
>>> Foo.bar is foo1.bar is foo2.bar
True
>>> Foo.bar, foo1.bar, foo2.bar
(['baz', 'bing'], ['baz', 'bing'], ['baz', 'bing'])

All inheritance means in Python is when you look up some attribute, some_obj.some_attribute, that you lookup that attribute in the namespaces you inherit. So if .some_attribute is looked up in some_obj, and it isn't found, then, the class namespace, and all the classes in the method resolution order are consulted (in order).

If some_obj is itself a class, you skip any instance lookup, and head straight for the class namespace and the namespaces in the method resolution order.

  • Related