How do overridden method calls from base-class methods work?

后端 未结 5 1359
我寻月下人不归
我寻月下人不归 2021-02-18 13:01

According to the docs on inheritance:

Derived classes may override methods of their base classes. Because methods have no special privileges when calling

5条回答
  •  眼角桃花
    2021-02-18 14:02

    To illustrate how it works consider these two classes:

    class Parent(object):
        def eat(self):
            print("I don't want to eat that {}.".format(self.takefrompocket()))
    
        def takefrompocket(self):
            return 'apple'
    
        def __getattribute__(self, name):
            print('Looking for:', name)
            method_to_use = object.__getattribute__(self, name)
            print('Found method:', method_to_use)
            return method_to_use
    
    class Child(Parent):
        def takefrompocket(self):
            return 'salad'
    

    The __getattribute__ method is responsible in new-style-classes (like all classes in python3) for the attribute lookup. It is just implemented to print what each lookup does - normally you don't want to and shouldn't implement it yourself. The lookup follows pythons method resolution order (MRO) just if you are really interested.

    >>> some_kid = Child()
    >>> some_kid.eat()
    Looking for: eat
    Found method: >
    Looking for: takefrompocket
    Found method: >
    I don't want to eat that salad.
    

    So when you want to use eat then it uses Parent.eat in this example. But self.takefrompocket is used from Child.

    >>> some_parent = Parent()
    >>> some_parent.eat()
    Looking for: eat
    Found method: >
    Looking for: takefrompocket
    Found method: >
    I don't want to eat that apple.
    

    Here both methods are taken from Parent. Inherited classes don't (generally) interfere with their ancestors!

提交回复
热议问题