如何从 Python 中的静态方法获取(子)类名? [英] How to get (sub)class name from a static method in Python?
本文介绍了如何从 Python 中的静态方法获取(子)类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我定义:
class Bar(object):
@staticmethod
def bar():
# code
pass
class Foo(Bar):
# code
pass
是否可以通过函数调用 Foo.bar() 来确定类名 Foo?
Is it possible for a function call Foo.bar() to determine the class name Foo?
推荐答案
用类方法替换静态方法.这将在调用时传递类,因此您可以从中获取类名.
Replace the staticmethod with a classmethod. This will be passed the class when it is called, so you can get the class name from that.
class Bar(object):
@classmethod
def bar(cls):
# code
print cls.__name__
class Foo(Bar):
# code
pass
>>> Bar.bar()
Bar
>>> Foo.bar()
Foo
这篇关于如何从 Python 中的静态方法获取(子)类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文