将静态变量作为参数传递给Class吗?

问题描述 投票:0回答:2

我如何实现这样的目标?

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被解释了,所以我也不知道这是否是更好的问题。

python class static-variables
2个回答
1
投票
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

2
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.