python函数多态 python的多态性( 二 )


pass
May = Child()
Peter = Person()
print(isinstance(May,Child))# True
print(isinstance(May,Person))# True
print(isinstance(Peter,Child))# False
print(isinstance(Peter,Person))# True
print(issubclass(Child,Person))# True
Python 类的多态
在说明多态是什么之前,我们在 Child 类中重写 print_title() 方法:若为male , print boy;若为female,print girl
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person):# Child 继承 Person
def print_title(self):
if self.sex == "male":
print("boy")
elif self.sex == "female":
print("girl")
May = Child("May","female")
Peter = Person("Peter","male")
print(May.name,May.sex,Peter.name,Peter.sex)
May.print_title()
Peter.print_title()
当子类和父类都存在相同的 print_title()方法时 , 子类的 print_title() 覆盖了父类的 print_title(),在代码运行时,会调用子类的 print_title()
这样 , 我们就获得了继承的另一个好处:多态 。
多态的好处就是,当我们需要传入更多的子类,例如新增 Teenagers、Grownups 等时,我们只需要继承 Person 类型就可以了,而print_title()方法既可以直不重写(即使用Person的),也可以重写一个特有的 。这就是多态的意思 。调用方只管调用 , 不管细节 , 而当我们新增一种Person的子类时 , 只要确保新方法编写正确,而不用管原来的代码 。这就是著名的“开闭”原则:
对扩展开放(Open for extension):允许子类重写方法函数
对修改封闭(Closed for modification):不重写 , 直接继承父类方法函数
子类重写构造函数
子类可以没有构造函数,表示同父类构造一致;子类也可重写构造函数;现在,我们需要在子类 Child 中新增两个属性变量:mother 和 father,我们可以构造如下(建议子类调用父类的构造方法 , 参见后续代码):
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
class Child(Person):# Child 继承 Person
def __init__(self,name,sex,mother,father):
self.name = name
self.sex = sex
self.mother = mother
self.father = father
May = Child("May","female","April","June")
print(May.name,May.sex,May.mother,May.father)
若父类构造函数包含很多属性,子类仅需新增1、2个,会有不少冗余的代码 , 这边,子类可对父类的构造方法进行调用,参考如下:
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
class Child(Person):# Child 继承 Person
def __init__(self,name,sex,mother,father):
Person.__init__(self,name,sex)# 子类对父类的构造方法的调用
self.mother = mother
self.father = father
May = Child("May","female","April","June")
print(May.name,May.sex,May.mother,May.father)
多重继承
多重继承的概念应该比较好理解 , 比如现在需要新建一个类 baby 继承 Child , 可继承父类及父类上层类的属性及方法,优先使用层类近的方法,代码参考如下:
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person):
pass
class Baby(Child):
pass
May = Baby("May","female")# 继承上上层父类的属性
print(May.name,May.sex)

推荐阅读