的Python:类和实例属性之间的区别 [英] Python: Difference between class and instance attributes

查看:109
本文介绍了的Python:类和实例属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时之间有任何有意义的区别:

Is there any meaningful distinction between:

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

VS

class B(object):
    def __init__(self, foo=5):
        self.foo = foo

如果你创建了很多实例,有没有在这两种风格的性能和空间要求的任何区别吗?当你读了code,你考虑的两种风格的意义是不同的显著?

If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?

推荐答案

除了性能方面的考虑,是有显著的语义的区别。在类属性的情况下,只有一个被称为对象。在实例属性设置在-实例,可以有称为多个对象。例如

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    
[]

这篇关于的Python:类和实例属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆