【问题标题】:Maintaining a common value of a static variable across instances in Python在 Python 中跨实例维护静态变量的公共值
【发布时间】:2017-05-10 11:35:04
【问题描述】:

我已经读过要创建一个静态变量,我们可以在类定义中而不是在方法中声明它们。但从 Java 世界来看,它对我来说似乎不是那么“静态”,因为从一个实例更改变量的值会创建自己的变量,不同于类变量。 我正在寻找一种方法来确保变量的值在不同的实例中保持一致。 StackOverflow 上的答案之一建议使用以下代码,这对我来说似乎效果不佳。

class Test(object):
_i = 3
@property
def i(self):
    return self._i
@i.setter
def i(self,val):
    self._i = val


x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # The example suggested no error here but it doesn't work for me

如果可以做到这一点,你能举例说明吗?

【问题讨论】:

  • 您似乎在浪费时间,因为没有常量变量,并且 python 中有动态属性,您是否考虑过不这样做(覆盖实例中的变量)?跨度>

标签: python class static class-variables


【解决方案1】:
class Test(object):
    _i = 3

    @classmethod
    def set_i(self, value):
        self._i = value

    def get_i(self):
        return self._i

    i = property(get_i, set_i)

x1 = Test()
x2 = Test()
print(x1.i) # 3
print(x2.i) # 3

x1.set_i(50)
print(x1.i) # 50
print(x2.i) # 50

【讨论】:

  • 这只会在 x1 实例的命名空间中创建 i 的新变量,因此不会影响 x2 中的任何内容。
  • 我明白了。好的,我已经使用类方法编辑了答案以更新类的静态变量。我确认这会起作用。
  • @NavjotSingh 好的,我现在给你买了一个更好的。
猜你喜欢
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 2010-10-13
  • 2015-03-19
  • 2021-11-23
相关资源
最近更新 更多