Get parent class name?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 | class A(object): def get_class(self): return self.__class__ class B(A): def __init__(self): A.__init__(self) b = B() print b.get_class() |
此代码将打印
如何获取定义方法的类名(即
文档:https://docs.python.org/2/reference/datamodel.html标准类型层次结构
类对象有一个
1 2 3 4 5 6 7 8 9 10 11 | >>> class Base(object): ... pass ... >>> class Derived(Base): ... def print_base(self): ... for base in self.__class__.__bases__: ... print base.__name__ ... >>> foo = Derived() >>> foo.print_base() Base |
inspect.getmro(cls) Return a tuple of class cls’s base classes,
including cls, in method resolution order. No class appears more than
once in this tuple. Note that the method resolution order depends on
cls’s type. Unless a very peculiar user-defined metatype is in use,
cls will be the first element of the tuple.
1 2 | import inspect inspect.getmro(B) |
结果将是:
1 | (<class '__main__.B'>, <class '__main__.A'>, <type 'object'>) |
第一个元素是类本身,第二个元素总是父元素的第一个。之后事情会变得更加复杂。
你可以改变
1 2 3 | return self.__class__ return A().__class__ |
因为没有其他的()实例可用…