python继承总结

参考来源:python类的继承

1.调用公共方法

#!/usr/bin/env python
# coding: utf-8

# # 1.调用公共方法

# In[1]:


class Father():
    def __init__(self):
        self.a='aaa'  
    def action(self):
        print('调用父类的方法')





class Son(Father):
    pass


# In[3]:


son=Son()     # 子类Son 继承父类Father的所有属性和方法
son.action()  # 调用父类方法
son.a         # 调用父类属性

2.重写override父类方法

# In[4]:


class Father():
    def __init__(self):
        self.a='aaa'
    
    def action(self):
        print('调用父类的方法')

class Son(Father):
    def __init__(self):
        self.a='bbb'
    def action(self):
        print('子类重写父类的方法')
        
son=Son()     # 子类Son继承父类Father的所有属性和方法
son.action()  # 子类Son调用自身的action方法而不是父类的action方法
son.a

3.调用父类私有

# In[5]:


class Father():
    def __action(self):  # 父类的私有方法
        print('调用父类的方法')
        
class Son(Father):
    def action(self):
        super()._Father__action()

son=Son()
son.action()

4.调用父类__init__方法

# In[8]:


class Father():
    def __init__(self):
        self.a='aaa'
    
class Son(Father):
    def __init__(self):
        pass

son = Son()
son.a

4.1改法一

# In[7]:


class Father():
    def __init__(self):
        self.a='aaa'
    
class Son(Father):
    def __init__(self):
        super().__init__()

son = Son()
son.a

4.2改法二

# In[9]:


class Father():
    def __init__(self):
        self.a='aaa'
    
class Son(Father):
    def __init__(self):
        Father.__init__(self) # 这里的self一定要加上

son = Son()
son.a

5.继承父类初始化过程中的参数

5.1 别忘了子类的dev函数,本身就存在继承关系

5.2 不能只关注__init__,还有其他的继承

# In[12]:


class Father():
    def __init__(self,a,b):
        self.a = a
        self.b = b
        
    def dev(self):
        return self.a - self.b
 
 #调用父类初始化参数a,b并增加额外参数c
class Son(Father):
    def __init__(self,a,b,c=10):  # 固定值: 例如默认c=10,也可以显式地将c赋值
        # Father.__init__(self,a,b) 
        super().__init__(a,b)
        self.c = c
        
    def add(self):
        return self.a+self.b
    
    def compare(self):
        if self.c > (self.a+self.b):
            return True
        else:
            return False
        
son=Son(1,2,1)     #  显式地将c=1传入子类初始化函数
print(son.dev())     # 调用父类dev函数
print(son.add())     # 子类自身add函数
print(son.compare()) # 子类自身compare函数

猜你喜欢

转载自blog.csdn.net/weixin_47289438/article/details/112763484