【问题标题】:Passing a static variable to a Class as argument?将静态变量作为参数传递给类?
【发布时间】:2020-05-25 02:31:34
【问题描述】:

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

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

[编辑]
一个更好的问题是“如何在运行时初始化一个类静态变量?”,但是 python 被解释了,所以我不知道这是否是一个更好的问题。

【问题讨论】:

  • 只有我一个人认为这看起来很可疑吗?这是XY 吗?
  • 如果你需要一个在所有类中都是常量的变量,然后各个对象彼此分开添加这个常量值来创建最终属性,那么为什么不直接创建最终值,保持这个值“常量”作为 init 的参数,甚至是 init 中的默认值,甚至只是硬编码?
  • 编写一个创建类并返回它的函数。
  • 您想要一种myClass 的某些值为static_var,还是您想要几种myClass 每个都有 static_var 的单独值?
  • 类定义被评估,它们可以访问该定义发生的范围(以及围绕它的词法)中的值。你可以定义一个static_variable,然后运行class代码,如果你去掉myClass之后的括号。

标签: python class static-variables


【解决方案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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2013-09-05
      • 1970-01-01
      相关资源
      最近更新 更多