调用自身类方法和父类方法

这篇很基础,主要是记录2个关于调用父类和子类的点:

  • C++和Java中调用自身类是用this,如果调用自身类的方法则用this.xxx_function,而python中调用自身类的方法是用self.xxx_function
  • Java和python调用父类的方法可以直接用super,但是C++没有super
  • 在C++中,子类和父类函数名一样的函数fun,如果参数不一样,不管加不加virtual,当子类调用fun()时,会先在子类中找,找不到会报错。

下面给个python栗子:

# !/usr/bin/python
# -*- coding: utf-8 -*-
class FooParent:
    def __init__(self):
        self.parent = 'I\'m the parent.'
        self.toy = "parent_funny_toy"
        print ('Parent')

    def bar(self,message):
        print ("%s from Parent bar function" % message)

class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        # super(FooChild,self).__init__()
        super().__init__()
        self.toy = "child_funny_toy"
        print ('Child')

    def bar(self,message):
        print("%s from child bar function" % message)

    def bar_test(self, message):
        # 第一种:使用super调用父类方法
        print('parent bar fuction:')     # super(FooChild, self).bar(message)
        super().bar(message)
        # 第二种:使用self调用自身方法
        print('child bar fuction:')
        print(self.bar(message))
        # 第三种(错误):使用this调用自身方法(java才是)
        # this.bar(message)

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar_test("abc")
# Parent
# Child
# parent bar fuction:
# abc from Parent bar function
# parent bar fuction:
# abc from child bar function

猜你喜欢

转载自blog.csdn.net/qq_35812205/article/details/126653056