具有非None类属性的类的新实例?

编程入门 行业动态 更新时间:2024-10-26 15:30:33
本文介绍了具有非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.

如果a和b属于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

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

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.b和Foo.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类属性的类的新实例?

本文发布于:2023-11-25 14:20:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630102.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   类属

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!