我想知道在初始化之前是否有办法在定义类属性时自动获取类名
class MyClass(object):
attribute1 = 1
attribute2 = 2 # This a simple example, MyClass has many other attributes
print className # normally one would use self.__class__.__name__ but self or cls are not defined at the level
def __init__(self):
a = 1
在我正在使用的框架中,attribute1和attribute2是对象实例(你会说在python中所有东西都是面向对象:))我想在MyClass初始化之前将类名设置为那些属性。 MyClass初始化了很多次,它有超过2个属性,这使得每次初始化操作都非常耗时
答案 0 :(得分:0)
元类可用于在类初始化之前使用类名设置属性:
class MyClassMeta(type):
def __init__(self, name, bases, attrs):
super(MyClassMeta, self).__init__(name, bases, attrs)
# Set class_name to the name of our class; in this case "MyClass"
self.class_name = name
class MyClass(object):
__metaclass__ = MyClassMeta
def __init__(self):
# Prints "MyClass"
print(self.class_name)
有关元类的详细说明,请参阅this answer。