python类的继承

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python类的继承相关的知识,希望对你有一定的参考价值。

面向对象的三大特性:封装、继承、多态
继承时面向对象编程的优点之一
类的继承与方法重载:
继承的特点:
减少代码和灵活定制新类
子类具有父类的属性和方法
子类不能继承父类的私有属性/方法
子类可以添加新的方法
子类可以修改父类的方法
继承的语法:
定义类时,在类名后:(继承的类名)
多重继承时,括号中放多个父类名,逗号分开
例子:class MyClass(BaseClass)
python中没有继承的类,默认继承Object
类名.base 类名.bases 查看父类
代码:

# -*- coding=utf-8 -*-
class A:
    pass

print(A.__base__)

class B(A):
    pass

print(B.__base__)

class C:
    pass

class D(A,C):
    pass

print(D.__bases__)

super() 父类
super.方法名() 调用父类方法
子类调用方法时,会先在子类找,子类不存在时,会向父类找

# -*- coding=utf-8 -*-
class Washer:
    company = "Le xi"
    def __init__(self,water=10,scour=2):
        self._water = water
        self.scour = scour
        self.year = 2010
        pass

    @staticmethod
    def spins_ml(spins):
        print("company:",Washer.company)
        return spins * 0.4

    @classmethod
    def get_washer(cls,water,scour):
        return cls(water,Washer.spins_ml(scour))

    @property
    def water(self):
        return self._water

    @water.setter
    def water(self,water):
        if 0 <= water <= 500:
            self._water = water
            pass
        else:
            print("输入的值有误!")
            pass
        pass

    @property
    def total_year(self):
        return 2015-self.year

    def set_water(self,water):
        self.water = water
        pass

    def set_scour(self,scour):
        self.scour = scour
        pass

    def add_water(self):
        print(‘Add water:‘,self.water)
        pass

    def add_scour(self):
        print(‘Add scour:‘,self.scour)
        pass

    def start_wash(self):
        self.add_water()
        self.add_scour()
        print(‘Start wash...‘)
        pass
    pass

# if __name__ == ‘__main__‘:
#     print(Washer.spins_ml(8))
#     w = Washer()
#     print(w.spins_ml(8))
#     w = Washer(200,Washer.spins_ml(9))
#     w.start_wash()
#     w = Washer.get_washer(200, 10)
#     w.start_wash()
#     pass

class WasherDry(Washer):
    def dry(self):
        print(‘Dry clothes...‘)
        pass
    #方法重载
#     def start_wash(self):
#         self.add_scour()
#         self.add_water()
#         print("Start wash...")
#         pass
#     pass
    #调用父类方法
    def start_wash(self):
        print("....")
        super().start_wash()
        print("......")

if __name__ == ‘__main__‘:
    w = WasherDry()
    w.start_wash()
    print(w.scour,w.company)
    w.dry()

以上是关于python类的继承的主要内容,如果未能解决你的问题,请参考以下文章

java 代码片段

python类的继承

Python类的继承

Python类的继承

Python类的继承

Python类的继承