python-mro

Method resolution order in python

纵饮孤独 提交于 2021-02-16 14:33:08
问题 I am new to python. I am using python 2.7. I was going through method order resolution with a small snippet as follows: class A(object): attr = 'A' class B(A): pass class C(A): attr = 'C' class D(B,C): pass x = D() print x.attr The order of resolution is x,D,B,C,A and hence the output would be C. Going by the above example, i made a small change to the code. class A(object): attr = 'A' class E(object): attr = 'E' class B(A): pass class C(E): attr = 'C' class D(B,C): pass x = D() print x.attr

Weird MRO result when inheriting directly from typing.NamedTuple

久未见 提交于 2020-05-29 04:07:27
问题 I am confused why FooBar.__mro__ doesn't show <class '__main__.Parent'> like the above two. I still don't know why after some digging into the CPython source code. from typing import NamedTuple from collections import namedtuple A = namedtuple('A', ['test']) class B(NamedTuple): test: str class Parent: pass class Foo(Parent, A): pass class Bar(Parent, B): pass class FooBar(Parent, NamedTuple): pass print(Foo.__mro__) # prints (<class '__main__.Foo'>, <class '__main__.Parent'>, <class '__main_