简体   繁体   中英

A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it

I am reading python documentaitin at: https://docs.python.org/3/tutorial/classes.html

I am having trouble understanding the following:

Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)

Say base class X has method A that calls method B in the same base class.

Now a derived class Y, say has method B, and user invokes YA(). Then, method A from Class X will be invoked and it will call method B from Class Y? Is this what author is trying to say?

I assume this it what he means

In [8]: class A:
   ...:     def foo(self):
   ...:         print ('foo')
   ...:         self.bar()
   ...:     def bar(self):
   ...:         print ('bar')
   ...:

In [9]: class B(A):
   ...:     def bar(self):
   ...:         print('bar but in b')
   ...:

In [10]: obj = B()

In [11]: obj.foo()
foo
bar but in b

In line 11, obj.foo() calls foo in class B, since its non existent, it goes to foo in class A, which then calls bar , since B has bar it calls it instead of bar in class A

If you have access to a debugger like pycharm it would be easier to follow it step by step

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM