Python(二十)继承

Posted on 2021-04-27 15:46  MissRong  阅读(60)  评论(0)    收藏  举报

Python(二十)继承

一、继承

class Person:
    def __init__(self):
        self.name = "张三"
        self.money = 50000000000
        self.house = "海上明珠"
    def play(self):
        print("就是玩儿!")
#类名(父类名)继承,子类继承父类,拥有父类公有方法和公有属性 不能继承私有属性
class Son(Person):
    def eat(self):
        print("就是吃")
class Girl(Person):
    pass
if __name__ == "__main__":
    #实例化对象
    s = Son()
    s.eat()
    #子类继承父类的公有方法
    s.play()
    #子类继承父类的公有属性
    print(s.money)    
    #子类不能继承父类私有属性
    #print(s.__name)
    g = Girl()
    g.play()
    

二、多继承

class A:
    def eat(self):
        print("方法A")
class B:
    def eat(self):
        print("方法B")
#多重继承
# 如果A中有eat()方法就调用A,否则就调用B
class C(A, B):
    pass
if __name__ == "__main__":
    c = C()
    c.eat()

三、继承构造方法

class Person:
    def __init__(self, name, money, house):
        self.name = name
        self.money = money
        self.house = house
    def play(self):
        print("就是玩儿!")
#类名(父类名)继承,子类继承父类,拥有父类公有方法和公有属性 不能继承私有属性
class Son(Person):
    def __init__(self):
        self.kk = "self"
    def eat(self):
        print("就是吃")

if __name__ == "__main__":
    #实例化对象
    # s = Son("张三", 3000, "house")

    #如果子类重写了构造方法,就不能调用父类的方法
    s = Son()
    s.eat()
    print(s.name)
    print(s.kk)
   
  

四、super

class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print("A中的eat()", self.name, self.age)

class B(A):
def __init__(self):
        super().__init__("张三", 18)
        self.sex = ""
    def eat(self):
        super().eat()
        print("1111111111111")
if __name__ == "__main__":
    b = B()
    b.eat()
    print(b.sex)

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3