具有非None类属性的类的新实例? [英] New instance of class with a non-None class attribute?

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

问题描述

我有一个Python类,该类的class属性设置为None以外的其他属性.创建新实例时,对该属性所做的更改将在所有实例中永久存在.

I have a Python class that has a class attribute set to something other than None. When creating a new instance, the changes made to that attribute perpetuates through all instances.

这里有一些代码可以理解这一点:

Here's some code to make sense of this:

 class Foo(object):
   a = []
   b = 2

 foo = Foo()
 foo.a.append('item')
 foo.b = 5

使用foo.a会返回['item'],而foo.b会返回5

Using foo.a returns ['item'] and foo.b returns 5, as one would expect.

当我创建一个新实例(我们将其称为bar)时,使用bar.a也会返回['item'],而bar.b也会返回5!但是,当我最初将所有类属性设置为None时,然后将它们设置为__init__中的任何内容,就像这样:

When I create a new instance (we'll call it bar), using bar.a returns ['item'] and bar.b return 5, too! However, when I initially set all the class attributes to None then set them to whatever in __init__, like so:

 class Foo(object):
   a = None
   b = None

   def __init__(self):
     self.a = []
     self.b = 2

使用bar.a返回[]bar.b返回2,而foo.a返回['item']foo.b返回5.

Using bar.a returns [] and bar.b returns 2 while foo.a returns ['item'] and foo.b returns 5.

这是假设工作的方式吗?很显然,在我编写Python的3年中,我从未遇到过这个问题,并且需要澄清一下.我也无法在文档的任何地方找到它,因此,如果可以的话,给我一个参考是很棒的. :)

Is this how it's suppose to work? I've apparently never ran into this issue in the 3 years I've programmed Python and would like some clarification. I also can't find it anywhere in the documentation, so giving me a reference would be wonderful if possible. :)

推荐答案

是的,这应该是这样工作的.

Yes, this is how it is supposed to work.

如果ab属于Foo instance ,则正确的方法是:

If a and b belong to the instance of Foo, then the correct way to do this is:

class Foo(object):
   def __init__(self):
     self.a = []
     self.b = 2

以下使得ab属于类本身,因此所有实例共享相同的变量:

The following makes a and b belong to the class itself, so all instances share the same variables:

class Foo(object):
   a = []
   b = 2

当您混合使用这两种方法时(如您在第二个示例中所做的那样),这并不会增加任何有用的信息,只会引起混乱.

When you mix the two methods -- as you did in your second example -- this doesn't add anything useful, and just causes confusion.

一个值得一提的警告是,当您在第一个示例中执行以下操作时:

One caveat worth mentioning is that when you do the following in your first example:

foo.b = 5

您未更改Foo.b,而是向foo添加了阴影" Foo.b的全新属性.执行此操作时,bar.bFoo.b都不会更改.如果随后执行del foo.b,则会删除该属性,并且foo.b将再次引用Foo.b.

you are not changing Foo.b, you are adding a brand new attribute to foo that "shadows" Foo.b. When you do this, neither bar.b nor Foo.b change. If you subsequently do del foo.b, that'll delete that attribute and foo.b will once again refer to Foo.b.

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

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