有没有办法在不显式使用类名的情况下访问类变量,以防我稍后决定更改类的名称?
像这样的东西
static_variable = 'stuff'
className = CLASS
def method (self):
className.static_variable
这可能以简单的方式吗?
回答
self.static_variable或 __class__.static_variable
有没有办法在不显式使用类名的情况下访问类变量,以防我稍后决定更改类的名称?
像这样的东西
static_variable = 'stuff'
className = CLASS
def method (self):
className.static_variable
这可能以简单的方式吗?
回答
self.static_variable或 __class__.static_variable
不要忘记阅读评论。
对于任何正在寻找答案的人来说,暂时不管混合静态变量和实例变量是否是一个好主意。
有两种简单的方法可以解决这个问题。
第一种方式
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