What is the difference between class and instance attributes?

后端 未结 5 1672
面向向阳花
面向向阳花 2020-11-21 05:44

Is there any meaningful distinction between:

class A(object):
    foo = 5   # some default value

vs.

class B(object):
    d         


        
5条回答
  •  孤城傲影
    2020-11-21 06:31

    Beyond performance considerations, there is a significant semantic difference. In the class attribute case, there is just one object referred to. In the instance-attribute-set-at-instantiation, there can be multiple objects referred to. For instance

    >>> class A: foo = []
    >>> a, b = A(), A()
    >>> a.foo.append(5)
    >>> b.foo
    [5]
    >>> class A:
    ...  def __init__(self): self.foo = []
    >>> a, b = A(), A()
    >>> a.foo.append(5)
    >>> b.foo    
    []
    

提交回复
热议问题