Python 使用类名访问静态变量
如果我以后决定更改类名,有没有一种方法可以在不显式使用类名的情况下访问类变量 像这样的Python 使用类名访问静态变量,python,class,static-methods,static-variables,class-names,Python,Class,Static Methods,Static Variables,Class Names,如果我以后决定更改类名,有没有一种方法可以在不显式使用类名的情况下访问类变量 像这样的 static_variable = 'stuff' className = CLASS def method (self): className.static_variable 这是否可能以一种简单的方式实现 回答 class MyClass(): static_variable = 'VARIABLE' def __init__(self): self.ins
static_variable = 'stuff'
className = CLASS
def method (self):
className.static_variable
这是否可能以一种简单的方式实现
回答
class MyClass():
static_variable = 'VARIABLE'
def __init__(self):
self.instanceVariable = 'test'
def access_static(self):
print(__class__.static_variable)
self.static\u variable或uuu class\uuu.static\u 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)
可以使用类静态变量或使用
self.static_变量,只要代码中没有为self.static_变量定义实例变量
但是,使用self会使访问静态变量还是实例变量变得模棱两可,因此我更喜欢的方法是在静态变量前面加上“class”而不是“ClassName.static”变量,如果你还是要依赖magic
\uuu class\uuuu
闭包变量吗?作为一条规则:在你的类中,你不需要知道类的名称(一个例外:super
在python-2.x中,可能在\uu repr\uu
或\uu str\uu
中)。每当您发现需要类的名称时,可能有更好/更简单的方法。@Rethipher:暂时忽略这些内容是类变量还是实例变量,您是否不知道可以通过self
读取类变量?@Rethipher何时需要区分self.foo
首先检查实例中名为foo
的属性,如果没有,则开始按MRO顺序将foo
作为基类的类属性。实例变量和类变量同名将是糟糕的设计。请停止将它们称为静态变量。它们被称为类变量;它们没有什么特别固定的地方。@chepner只要你知道它的功能,你叫它什么其实并不重要。我在Matlab、Simulink、Python、C、C++和java之间来回穿梭。他们都把这些称为不同的概念。我怎么强调这个名字都不重要,它很重要。例如,静态方法和类方法之间有很大的区别。你可能知道你所说的静态变量是什么意思;不要以为别人会。