2

有没有办法在不显式使用类名的情况下访问类变量,以防我稍后决定更改类的名称?

像这样的东西

static_variable = 'stuff'

className = CLASS

def method (self):
    className.static_variable

这可能以简单的方式吗?

回答

self.static_variable __class__.static_variable

4

1 回答 1

0

不要忘记阅读评论。


对于任何正在寻找答案的人来说,暂时不管混合静态变量和实例变量是否是一个好主意。

有两种简单的方法可以解决这个问题。

第一种方式

class MyClass():
    static_variable = 'VARIABLE'

    def __init__(self):
        self.instanceVariable = 'test'

    def access_static(self):
        print(__class__.static_variable)

第二种方式

class MyClass():
    static_variable = 'VARIABLE'

    def __init__(self):
        self.instanceVariable = 'test'

    def access_static(self):
        print(self.static_variable)

可以使用.static_variable 或使用 self.static_variable 访问实例变量,只要在代码中的某处没有为 self.static_variable 定义实例变量。

使用 self 会使您是否正在访问静态变量或实例变量变得模棱两可,所以我首选的方法是简单地在static_variable前面加上class而不是 ClassName.static_variable

于 2017-05-31T20:48:16.493 回答