Skip to main content
 首页 » 编程设计

python之使用 Python 类名定义类变量

2025年05月04日12linjiqin

我有课

class MyClass(object): 
    ClassTag = '!' + 'MyClass' 

我不想显式分配 'MyClass',而是想使用一些结构来获取类名。如果我在类函数中,我会做类似的事情

@classfunction 
def Foo(cls): 
    tag = '!' + cls.__class__.__name__ 

但这里我在类范围内,但不在任何函数范围内。解决这个问题的正确方法是什么?

非常感谢

请您参考如下方法:

Instead of explicitly assigning 'MyClass' I would like to use some construct to get the class name.

您可以使用类装饰器结合类对象的 __name__ 属性来完成此操作:

def add_tag(cls): 
    cls.ClassTag = cls.__name__ 
    return cls 
 
@add_tag 
class Foo(object): 
    pass 
 
print(Foo.ClassTag) # Foo 

除上述内容外,还有一些旁注:

  • 从上面的例子可以看出,类是使用 class 关键字,而不是 def 关键字。 def 关键字用于 定义函数。我建议浏览 the tutorial provided by Python , 掌握 Python 基础知识。

  • 如果您不处理遗留代码或需要 Python 2 库的代码,我强烈推荐 upgrading to Python 3 .除了 Python 基金会将在 2020 年停止支持 Python 之外,Python 3 还修复了 Python 2 的许多怪癖,并提供了新的有用功能。如果您正在寻找有关如何从 Python 2 过渡到 3 的更多信息,一个不错的起点是 here。 .