我如何实现这样的目标?
class myClass(static_variable):
static_var = static_variable
def __init__(self, x):
self.x = x + static_var
obj = myClass(static_variable = 3)(x = 5)
#obj.x = 8
[EDIT]
更好的问题是“如何在运行时初始化类静态变量?”,但是python被解释了,所以我也不知道这是否是更好的问题。
答案 0 :(得分:1)
class
语句在运行时进行评估,并且可以访问其封闭范围。这样可以从上下文或通过执行其他代码来初始化类(“静态”)属性。
static_variable = 32
class myClass:
cvar1 = static_variable # lookup variable from enclosing scope
cvar2 = random.random() # call function to initialise attribute
def __init__(self, x):
self.x = x + self.cvar1 + self.cvar2
答案 1 :(得分:0)
您的第二行将解决问题。您无需随后在构造函数中分配它。
class YourClass:
static_var = 3*6 . # <--- assigns the static variable to a computed value, 18 in this case
def __init__(self):
pass
instance = YourClass()
print(instance.static_var) # <--- this will print 18
print(YourClass.static_var) # <--- this also prints 18