在 python 中初始化静态 class 属性
Initialize static class atributes in python
我有以下class
class Test:
x = None # this is a static variable common to all object created from this class
@classmethod
def initializeX(cls):
cls.x = 5
请注意 x
在实践中是一个对象,它需要由这个 class 创建的所有对象共有,我不能写例如 x = 5
所以我需要一个函数来初始化它。那么我怎样才能调用只初始化 x 一次而不是为每个创建的对象初始化的函数呢?在 python 中跳过 x = None
并直接在 initializeX(cls)
中定义 x 通常也是好的做法吗?
在 class 构造函数中,您可以编写一个 if 检查以查看 class 属性是否已经创建
if Test.x is None:
# Do initialization
你有什么理由不能做这样的事情吗?
def _new_x():
return [1, 2, 3] # <~~ whatever obj you need to initialize
class Test:
x = _new_x()
instance_a = Test()
instance_b = Test()
# note they're the same:
assert instance_a.x is instance_b.x
您可以在 class 级别初始化(并设置)它。
class Test:
x = None # this is a static variable common to all object created from this class
@classmethod
def initializeX(self, cls):
type(cls).x = 5 # Test.x
c1 = Test()
c2 = Test()
c1.initializeX(c1)
print(c1.x) # 5
print(c2.x) # 5
Test.x = 10
print(c1.x) # 10
print(c2.x) # 10
输出
5
5
10
10
我有以下class
class Test:
x = None # this is a static variable common to all object created from this class
@classmethod
def initializeX(cls):
cls.x = 5
请注意 x
在实践中是一个对象,它需要由这个 class 创建的所有对象共有,我不能写例如 x = 5
所以我需要一个函数来初始化它。那么我怎样才能调用只初始化 x 一次而不是为每个创建的对象初始化的函数呢?在 python 中跳过 x = None
并直接在 initializeX(cls)
中定义 x 通常也是好的做法吗?
在 class 构造函数中,您可以编写一个 if 检查以查看 class 属性是否已经创建
if Test.x is None:
# Do initialization
你有什么理由不能做这样的事情吗?
def _new_x():
return [1, 2, 3] # <~~ whatever obj you need to initialize
class Test:
x = _new_x()
instance_a = Test()
instance_b = Test()
# note they're the same:
assert instance_a.x is instance_b.x
您可以在 class 级别初始化(并设置)它。
class Test:
x = None # this is a static variable common to all object created from this class
@classmethod
def initializeX(self, cls):
type(cls).x = 5 # Test.x
c1 = Test()
c2 = Test()
c1.initializeX(c1)
print(c1.x) # 5
print(c2.x) # 5
Test.x = 10
print(c1.x) # 10
print(c2.x) # 10
输出
5
5
10
10