类和实例属性有什么区别? [英] What is the difference between class and instance attributes?

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

问题描述

是否有任何有意义的区别:

A 类(对象):foo = 5 # 一些默认值

对比

B 类(对象):def __init__(self, foo=5):self.foo = foo

如果您要创建大量实例,这两种样式在性能或空间要求上是否有任何差异?看代码的时候,是不是觉得这两种样式的含义有很大的不同?

解决方案

存在显着的语义差异(超出性能考虑):

  • 在实例上定义属性时(这是我们通常所做的),可以引用多个对象.每个都有一个完全独立的属性版本.
  • 当属性在类上定义时,只有一个底层对象被引用,所以如果对该类的不同实例的操作都试图设置/(append/extend/insert/etc.) 属性,然后:
    • 如果属性是内置类型(如 int、float、boolean、string),对一个对象的操作将覆盖(破坏)该值
    • 如果属性是可变类型(如列表或字典),我们将获得不必要的泄漏.

例如:

<预><代码>>>>A类:foo = []>>>a, b = A(), A()>>>a.foo.append(5)>>>b.foo[5]>>>A类:... def __init__(self): self.foo = []>>>a, b = A(), A()>>>a.foo.append(5)>>>b.foo[]

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

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?

解决方案

There is a significant semantic difference (beyond performance considerations):

  • when the attribute is defined on the instance (which is what we usually do), there can be multiple objects referred to. Each gets a totally separate version of that attribute.
  • when the attribute is defined on the class, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
    • if the attribute is a builtin type (like int, float, boolean, string), operations on one object will overwrite (clobber) the value
    • if the attribute is a mutable type (like a list or a dict), we will get unwanted leakage.

For example:

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

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

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