有没有一种方法可以访问类变量而不显式使用类名,以防万一我决定稍后更改类的名称?使用类名访问静态变量
像这样的事情
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中定义。
采用自主将使暧昧是否你虽然访问静态变量或实例变量,所以我首选做这件事的方式是简单地在前面加上static_variable与_class_而不是ClassName.static_variable
你不是只是在做'self.TABLE'吗? – user2357112
或'__class __。TABLE',如果你打算依赖魔术'__class__'闭包变量呢? – user2357112
作为一个重要的规则:在你的类内部你不需要知道类的名字(一个例外:在python-2.x中的'super',也许在'__repr__'或'__str__'中)。每当你发现你需要你班级的名字时,可能会有更好/更简单的方法。 – MSeifert