Home > Net >  When does Python fall back onto class __dict__ from instance __dict__?
When does Python fall back onto class __dict__ from instance __dict__?

Time:06-02

Please see the below snippet:

class Foo:
    class_var = "hi"

foo = Foo()
assert foo.class_var is Foo.class_var
assert "class_var" in Foo.__dict__
assert "class_var" not in foo.__dict__

All assertions here pass, though I am not sure if it's surprising that the identity assertion passes.

When and how does Python fall back onto a class __dict__ from an instance __dict__?

CodePudding user response:

As far as I know when foo.class_var is called the following steps happen:

  • Python starts to look for class_var in the namespace of the foo object.
  • If it finds it, it returns it.
  • In this case however it doesn't find it so it looks in the type of foo, which is Foo.
  • It finds it in Foo and returns it.

CodePudding user response:

You should know the difference between a "class attribute" and an "instance attribute", in your example, you have class_var which is class attribute, in the first assert statement, it check if class_var is in the instance of Foo , it pass, that because foo is of type Foo let's try another more clear examples here:

class Foo:
    var1 = "Hello"
    def __init__(self,var2):
        self.var2 = var2
foo = Foo("Hello")
assert foo.var1 is Foo.var1
assert "var1" in Foo.__dict__
assert "var2" in foo.__dict__
assert "var1" in foo.__dict__

notice something, the last assert statement is gonna raise an error, because var1 here is a class attribute, not instance attribute.

  • Related