Class Variable behaving like Instance Variable (Python 3.4)

前端 未结 3 560
别跟我提以往
别跟我提以往 2021-01-21 21:03

Python 3.4.0a1
Windows 8.1

Class Created:

class Bank(object):  
    bankrupt = False  

Command entered in IDLE __main__

3条回答
  •  广开言路
    2021-01-21 21:28

    After assignment to instance variable it is created if it was not before. And next time You try to access it You got it from instance __dict__.

    >>> class A:
    ...     foo = 'b'
    ...     bar = []
    ... 
    >>> a = A()
    >>> b = A()
    >>> a.__dict__
    {}
    >>> a.foo = 'c'
    >>> a.foo
    'c'
    >>> a.__dict__
    {'foo': 'c'}
    

    This is why You have different values for a.foo and b.foo Meanwhile If You modify variable (not reassign it) You will got result which You have described.

    >>> a.bar.append(1)
    >>> b.bar
    [1]
    >>> a.bar
    [1]
    >>> a.__dict__
    {'foo': 'c'}
    

    In this case instance variable was not created.

提交回复
热议问题