简体   繁体   English

python中的类变量初始化

[英]Class variable initialization in python

I have a class with a variable that should be an instance of this class. 我有一个带有变量的类,该变量应该是此类的实例。 I can't create an instance at the declaration line because python interpreter does not know how to construct object at that moment. 我无法在声明行创建实例,因为python解释器当时不知道如何构造对象。 There is a possible workaround: initializing after the class declaration. 有一个可能的解决方法:在类声明之后进行初始化。

class A(object):
    static_variable = None

    def some_method(self, a=static_variable):
       print a

A.static_variable = A()

But I need to use that class variable as a default argument. 但是我需要使用该类变量作为默认参数。 It is possible to solve the problem this way: 可以通过以下方式解决问题:

def some_method(self, a=None):
    a = a if a else A.static_variable
    print a

However, it looks very nonpythonic to me. 但是,对我来说,这看起来非常不合逻辑。 Any suggestion about how to use this kind of static variable as a default argument would be appreciated. 关于如何使用这种静态变量作为默认参数的任何建议将不胜感激。

Python does not support 'static' variables in the sense that languages like C++ do. Python不像C ++这样的语言支持“静态”变量。 So in this case, 'static_variable' is actually a class variable which is why you are encountering this problem. 因此,在这种情况下,“ static_variable”实际上是一个类变量,这就是您遇到此问题的原因。 I'm sure you already know this, but others may stumble here someday and see us calling it a static variable so it seems like we should clear that up for posterity. 我相信您已经知道这一点,但是其他人可能有一天会在这里绊倒,看到我们将其称为静态变量,因此似乎我们应该为后代进行清理。

I was thinking that since 'static_variable' is still a member of class A, then maybe there was a way around by not using it as an argument at all. 我当时在想,既然“ static_variable”仍然是A类的成员,那么也许可以通过完全不将其用作参数来解决。

Can you use a keyword argument in some_method()? 可以在some_method()中使用关键字参数吗?

instead of using it as a default argument to the function, you could just call the variable 'A.static_variable' if the kwarg was not used. 如果不使用kwarg,则可以仅将变量用作“ A.static_variable”,而不是将其用作函数的默认参数。

class A(object):
    static_variable = None

    def some_method(self, *, a=None):
        if a:
            print(a)
        else:
            print(A.static_variable)

A.static_variable = A()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM