在Python 3.5中,如何将类名分配给类变量?显而易见的替代方法是对类名进行硬编码。
class Foo(object):
the_module = __name__
also_the_module = __module__
def name_of_module(self):
return __name__
def name_of_class(self):
return __class__.__name__
print("Foo.the_module= ", Foo.the_module)
print("Foo.also_the_module= ", Foo.also_the_module)
print("Foo.__name__= ", Foo.__name__) # what is desired but outside of class def
print("Foo().name_of_module=", Foo().name_of_module())
print("Foo().name_of_class= ", Foo().name_of_class()) # what is desired but inside a method
我尝试从@classmethod
的第一个参数中获取该类。
class Foo(object):
@classmethod
def class_name(cls):
return cls.__name__
# Both of these produce the correct response but neither
# can be used assign to a class variable
print("Foo.class_name()= ", Foo.class_name())
print("Foo().class_name()= ", Foo().class_name())
不幸的是,在分配给类变量时无法调用此函数。 class = class_name
生产NameError: name 'class_name' is not defined
。 my_class = Foo.class_name()
生产NameError: name 'Foo' is not defined
。
注意:更新了问题以使用正确的Python术语“类变量”而不是静态变量(反映我的C ++背景)
注意有类方法
@classmethod
def class_name(cls):
return cls.__name__
与直接调用x.__class__.__name__
相比,没有任何结果。
如果要分配类名,只需修改类本身:
class Foo(object):
@classmethod
def class_name(cls):
return cls.__name__
Foo.__name__ = "bar"
a = Foo()
print(a.class_name())
输出bar
如果只想为一个实例使用不同的类名,则需要动态创建一个新类(继承旧类)并更改该类的名称。
def set_class_name(instance, new_class_name):
orig_class = instance.__class__
class _new_class(orig_class):
pass
_new_class.__name__ = new_class_name
a.__class__ = _new_class
a = Foo()
set_class_name(a, 'bar')
print(a.class_name())
也输出bar
。
class Foo(object):
def __init__(self):
self.class_name = self.__class__.__name__
x = Foo()
x.class_name
编辑Waitaminute。我不认为我能得到你。静态变量是什么意思?