开发相关知识

python - 类的继承

2019-08-02  本文已影响28人  暖A暖

什么是继承

继承是一种创建类的方法,一个类可以继承一个或多个父类,原始类称为基类或超类。
继承可以很方便的帮助子类拥有父类的属性和方法,减少代码冗余,子类可以定义自己的方法和属性,也可以覆盖父类的方法和属性。

实现继承

class Animal():
    def __init__(self, kind, age):
        self.kind = kind
        self.age = age
        print("这是父类的__init__方法")
    def info(self):
        print('这是一只' + self.kind, ',今年' + self.age + '岁了')

animal = Animal('狗', '5')
animal.info()

# 这是父类的__init__方法
# 这是一只狗 ,今年5岁了
class Cat(Animal):
    pass # 不想向类中添加任何其他的属性或者方法,可以使用关键字pass

cat = Cat('猫','3')
cat.info()

# 这是父类的__init__方法
# 这是一只猫 ,今年3岁了
class Cat(Animal):
    def __init__(self, kind, age, name):
        self.kind = kind
        self.age = age
        self.name = name
        print("这是子类的__init__方法")
    def info(self):  # 如果在子类中添加一个父类同名的方法,会覆盖父类的方法
        print('这是一只' + self.kind, ',今年' + self.age + '岁了', '它的名字是'+self.name)

cat = Cat('猫, '3', 'xixi')
cat.info()

# 这是子类的__init__方法
# 这是一只猫,今年3岁了 它的名字是xixi

如上所示,在子类中添加了一个info()方法,这是一个和父类中的方法同名的方法,会覆盖父类原有的方法。当你需要子类中用特殊或不同的功能时就可以这样做。

多继承

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    ...
    <statement-N>

需要注意圆括号中基类(父类)的顺序,若是基类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找基类中是否包含方法。

class Parent(object):
    def info(self):
        print('This is Parent')
    def show(self):
        print("show time")


class A(Parent):  # 继承Parent
    def info(self):  # 自动覆盖父类的此方法
        print('This is A')


class B(Parent):  # 继承Parent
    def info(self):
        print('This is B')


class C(A, B):  # 继承A,B
    pass

a = A()
a.info()  
# 输出:This is A

a.show()  
# 输出:show time
b = B()
b.info()  
# 输出:This is B

a.show()  
# 输出:show time
c = C()
c.info()  
# 输出: This is A

参考:https://www.9xkd.com/course/1039962250.html

上一篇 下一篇

猜你喜欢

热点阅读