Python mro() method All In One

xgqfrms / 2023-09-04 / 原文

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
>>> 

image

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.

  1. print(type(num).mro()):

    • num is a function.
    • type(num) returns the type of num, which is <class 'function'>.
    • type(num).mro() will give the method resolution order for the function class, which is [<class 'function'>, <class 'object'>].
  2. print(type(num)):

    • This is just printing the type of the num function, which is <class 'function'>.
  3. print(function.mro()):

    • Here, you're trying to access the mro method of something named function, but there's no such built-in name in Python. That's why you're getting a NameError.

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
>>> 

refs

https://www.python.org/download/releases/2.3/mro/

https://stackoverflow.com/questions/2010692/what-does-mro-do



©xgqfrms 2012-2021

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!