Python 反思:mro() 方法存在于何处?
Python introspection: Where does the mro() method live?
我试图获得对 python 内省的基本理解,在这样做的过程中,我发现在这方面有用的 mro()
方法提到 .
当我(作为自省练习)尝试使用上述方法和内置 dir()
函数试图找出 mro()
可能存在的位置时,我却无法成功。为什么?
这是我的方法:
mro()
方法显然无需任何导入即可使用(不像 inspect.getmro()
是 inspect
模块的一部分;例如 str.mro()
returns[<class 'str'>, <class 'object'>]
因为str.mro()
returns[<class 'str'>, <class 'object'>]
,mro()
方法应该存在于str
and/orobject
.
然而 dir(str)
和 dir(object)
似乎都没有包含 mro() 方法。还有help()和help(str.mro)不开导自省迷茫的同学
如果您使用 dir(type)
查看,您会发现 魔术方法 属性 __mro__
。引自 here:
class.__mro__
This attribute is a tuple of classes that are considered when looking for base classes during method resolution.
class.mro()
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in mro
查看 this answer 了解更多关于 type
的信息,它是 Python 中常用的元类。从那里引用:
type
is the usual metaclass in Python. type
is itself a class, and it is its own type. You won't be able to recreate something like type
purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type
.
我试图获得对 python 内省的基本理解,在这样做的过程中,我发现在这方面有用的 mro()
方法提到
当我(作为自省练习)尝试使用上述方法和内置 dir()
函数试图找出 mro()
可能存在的位置时,我却无法成功。为什么?
这是我的方法:
mro()
方法显然无需任何导入即可使用(不像inspect.getmro()
是inspect
模块的一部分;例如str.mro()
returns[<class 'str'>, <class 'object'>]
因为
str.mro()
returns[<class 'str'>, <class 'object'>]
,mro()
方法应该存在于str
and/orobject
.然而
dir(str)
和dir(object)
似乎都没有包含 mro() 方法。还有help()和help(str.mro)不开导自省迷茫的同学
如果您使用 dir(type)
查看,您会发现 魔术方法 属性 __mro__
。引自 here:
class.__mro__
This attribute is a tuple of classes that are considered when looking for base classes during method resolution.
class.mro()
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in mro
查看 this answer 了解更多关于 type
的信息,它是 Python 中常用的元类。从那里引用:
type
is the usual metaclass in Python.type
is itself a class, and it is its own type. You won't be able to recreate something liketype
purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclasstype
.