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

Passing a static variable to a Class as argument?

我怎样才能实现这样的目标?

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

[编辑]
一个更好的问题是 'How to initialize a class static variable at runtime ?',但是 python 被解释了,所以我也不知道这是否是一个更好的问题。

你的第二行就可以了。您不需要随后在构造函数中分配它。

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

class 语句在运行时进行计算,它可以访问其封闭范围。这允许从上下文或通过执行其他代码来初始化 class ("static") 属性。

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