2024-10-17 06:31:59 发布
网友
我有一节课
class MyClass(object): ClassTag = '!' + 'MyClass'
我不想显式地分配'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__属性结合使用来实现这一点:
__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的基本知识。
class
def
如果您不使用遗留代码或需要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)
您可以将类装饰器与类对象的
__name__
属性结合使用来实现这一点:除上述内容外,以下是一些旁注:
从上面的例子可以看出,类是使用
class
关键字,而不是def
关键字。def
关键字用于 定义函数。我建议你穿过the tutorial provided by Python, 掌握Python的基本知识。如果您不使用遗留代码或需要python2库的代码,我强烈建议使用upgrading to Python 3。除了Python基金会将在2020年停止支持Python之外,python3还修复了python2的许多怪癖,并提供了新的、有用的特性。如果您想了解更多关于如何从python2过渡到python3的信息,那么最好从here开始。
一个简单的方法是编写一个decorator:
相关问题 更多 >
编程相关推荐