首页 > Python3教程 > Python3类与面向对象

Python3 继承与多态

继承是用已写好的类的定义作为基础建立新类的技术,新类的定义能增加新的数据或新的功能,也能用父类的功能。

通过使用继承我们能够非常方便地复用以前的代码,能够大大的提高开发的效率。

继承

我们定义一个类的时候,如果从某个现有的类继承,新的累称为子类(Subclass),

而被继承的类称为基类、父类或超类(Base class、Super class)。

Python 支持类的继承。派生类的定义如下所示:

class DerivedClassName(BaseClassName1):

    <statement-1>

    <statement-N>

需要注意圆括号中基类的顺序,若是基类中有相同的方法名,而在子类使用时未指定,

python从左至右搜索 即方法在子类中未找到时,从左到右查找基类中是否包含方法。

BaseClassName(基类名)必须与派生类定义在一个作用域内。

除了类,还可以用表达式,基类定义在另一个模块中时就用这种写法:

class DerivedClassName(modname.BaseClassName):

  

方法重写

如果你的父类方法的功能不能满足你的需求,就在子类重写你父类的方法

class Animal(object):
def run(self):
print('Animal is running...')

class Cat(Animal):
# 子类增加新方法
def eat(self):
print('Cat eating fish...')
# 子类重写父类方法
def run(self):
print('Cat is running...')

def run_twice(a):
a.run()
a.run()

a = Animal()
c = Cat()

print('a is Animal?', isinstance(a, Animal))
print('a is Cat?', isinstance(a, Cat))
print('c is Animal?', isinstance(c, Animal))

run_twice(c)

Python3 继承与多态

多继承

Python同样有限的支持多继承形式。多继承的类定义形如下例:

class DerivedClassName(Base1, Base2, Base3):

    <statement-1>

    <statement-N>

需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,

python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。

 

运算符重载

Python同样支持运算符重载,我们能对类的专有方法进行重载

class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self ,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2 ,9)
v2 = Vector(5 ,-3)
print (v1 + v2) # 输出 Vector (7, 6)

 

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。