Compound assignment to Python class and instance variables

前端 未结 5 1963
天涯浪人
天涯浪人 2020-12-10 18:04

I\'ve been trying to understand Python\'s handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a

5条回答
  •  眼角桃花
    2020-12-10 18:41

    bar.num += 1
    

    creates a new instance variable 'num' on the 'bar' instance because it doesn't yet exist (and then adds 1 to this value)

    an example:

    class Foo:
      def __init__(self):
        self.num= 1
    
    bar = Foo()
    print bar.num
    

    this prints 1

    print bar.foo
    

    this gives an error as expected: Traceback (most recent call last): File "", line 1, in AttributeError: Foo instance has no attribute 'foo'

    bar.foo = 5
    print bar.foo
    

    now this prints 5

    so what happens in your example: bar.num is resolved as Foo.num because there's only an class attribute. then foo.num is actually created because you assign a value to it.

提交回复
热议问题