在多个Python实例中更改变量 [英] Changing variables in multiple Python instances

查看:134
本文介绍了在多个Python实例中更改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有同时设置类的所有实例的变量吗?我有一个简单的例子如下:

Is there anyway to set the variables of all instances of a class at the same time? I've got a simplified example below:

class Object():
   def __init__(self):
       self.speed=0

instance0=Object()
instance1=Object()
instance2=Object()

#Object.speed=5 doesn't work of course

我可以看到,通过添加所有新的实例一个列表,并用isinstance()迭代,但这是不可取的。

I can see it would be possible by adding all new instances to a list and iterating with isinstance(), but that's not desirable.

推荐答案

,是将你的属性总是作为一个类属性。如果它在类体上设置,并且对属性的所有写访问都是通过类名,而不是一个实例,这将工作:

One, simpler way, as the other answers put it, is to keep your attribute always as a class attribute. If it is set on the class body, and all write access to the attribute is via the class name, not an instance, that would work:

>>> class Object(object):
...     speed = 0
... 
>>> a = Object()
>>> b = Object()
>>> c = Object()
>>> 
>>> Object.speed = 5
>>> print a.speed
5
>>> 

但是,如果你在一个实例中设置属性,它自己的属性,它将不再随其他实例的变化而改变:

However, if you ever set the attribute in a single instance doing it this way, the instance will have its own attribute and it will no longer change along with the other instance's:

>>> a.speed = 10
>>> Object.speed = 20
>>> print b.speed
20
>>> print a.speed
10
>>>

为了克服这个问题,每当在任何实例中设置属性时, ,更容易的方法是将对象作为一个属性 - 其设置器设置类属性:

To overcome that, so that whenever the attribute is set in any instance, the class attribute itself is changed, the easier way is to have the object as a property - whose setter sets the class attribute instead:

class Object(object):
  _speed = 0
  @property
  def speed(self):
     return self.__class__._speed
  @speed.setter
  def speed(self, value):
     self.__class__._speed = value

>

Which works:

>>> 
>>> a = Object()
>>> b = Object()
>>> a.speed, b.speed
(0, 0)
>>> a.speed = 10
>>> a.speed, b.speed
(10, 10)

独立属性在实例上,但是一个特殊的set_all方法将在所有实例中设置属性,要走的方法是使用标准librayr中的gc(Garbage Collector)模块,找到并循环遍历该类的所有实例,并设置它们的实例属性:

If you want to have independent attribute on the instances, but a special "set_all" method that would set the attribute in all instances, the way to go is to use the gc (Garbage Collector) module in standard librayr, to find and loop through all instances of the class, and set their instance attributes:

import gc

class Object(object):
    def __init__(self):
        self.speed = 0

    def set_all_speed(self, value):
        for instance in (obj for obj in gc.get_referrers(self.__class__) if isinstance(obj, self.__class__)):
            instance.speed = value

其结果是:

>>> a  =Object()
>>> b = Object()
>>> a.speed = 5
>>> b.speed = 10
>>> a.speed, b.speed
(5, 10)
>>> a.set_all_speed(20)
>>> a.speed, b.speed
(20, 20)

这篇关于在多个Python实例中更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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