Python mro() method All In One
Python mro() method All In One
MRO:
Method Resolution Order
/方法解析顺序
error ❌
>>> function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>
solution
In Python, everything is an object
, including classes, functions, and primitive data types.
The mro
method stands for Method Resolution Order
, and it's available on class objects to determine the order in which base classes are considered when looking up a method.
This is especially useful for understanding multiple inheritance.
-
print(type(num).mro())
:num
is a function.type(num)
returns the type ofnum
, which is<class 'function'>
.type(num).mro()
will give the method resolution order for the function class, which is[<class 'function'>, <class 'object'>]
.
-
print(type(num))
:- This is just printing the type of the
num
function, which is<class 'function'>
.
- This is just printing the type of the
-
print(function.mro())
:- Here, you're trying to access the
mro
method of something namedfunction
, but there's no such built-in name in Python. That's why you're getting aNameError
.
- Here, you're trying to access the
The confusion might be stemming from how you're trying to access the mro
for functions.
For classes like int
and dict
, you can directly call int.mro()
and dict.mro()
, respectively, because int
and dict
are both class objects themselves.
However, there's no built-in function
class in Python you can directly reference.
https://stackoverflow.com/questions/77036308/python-how-to-get-mro-of-function-object-explicitly
demos
$ py3
>>> list
<class 'list'>
>>> print(list.mro())
[<class 'list'>, <class 'object'>]
>>> print(type([]).mro())
[<class 'list'>, <class 'object'>]
>>> print(type(list).mro())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method type.mro() needs an argument
>>>
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://www.python.org/download/releases/2.3/mro/
https://stackoverflow.com/questions/2010692/what-does-mro-do
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17677820.html
未经授权禁止转载,违者必究!