使用Python类名定义类变量

2024-10-17 06:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节课

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

我不想显式地分配'MyClass',而是想使用一些构造来获取类名。如果我在一个类函数中,我会这样做

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

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

非常感谢


Tags: 方法函数nameobjectfoodeftagmyclass
2条回答

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的基本知识。

  • 如果您不使用遗留代码或需要python2库的代码,我强烈建议使用upgrading to Python 3。除了Python基金会将在2020年停止支持Python之外,python3还修复了python2的许多怪癖,并提供了新的、有用的特性。如果您想了解更多关于如何从python2过渡到python3的信息,那么最好从here开始。

一个简单的方法是编写一个decorator:

def add_tag(cls):
    cls.ClassTag = cls.__name__
    return cls

# test

@add_tag
class MyClass(object):
    pass

print(MyClass.ClassTag)

相关问题 更多 >