亲宝软件园·资讯

展开

Python继承、多态 Python面向对象程序设计之继承、多态原理与用法详解

随风行云 人气:0

本文实例讲述了Python面向对象程序设计之继承、多态原理与用法。分享给大家供大家参考,具体如下:

相关内容:

继承:多继承、super、__init__、重写父类变量或函数

多态


继承:

class SchoolPerson:
  def study(self):
    print("it's time to study")

class Student(SchoolPerson):#继承的方法
  pass

a=Student()
a.study()

----------------------
结果:
it's time to study

上述结果显示,Student继承了SchoolPerson中的study函数

class SchoolPerson:
  def __init__(self,name,age,sex,mid):
    self.name=name
    self.age=age
    self.sex=sex
    self.mid=mid
  def study(self):
    print("it's time to study")

class Student(SchoolPerson):#继承的方法
  def __init__(self,name,age,sex,mid,grade):
    # super(Student,self).__init__(name,age,sex,mid)
    SchoolPerson.__init__(self,name,age,sex,mid)
    self.grade=grade
  def study(self):
    print("i am student,i want to study")

a=Student('A',18,'m','001',1)
a.study()
print(a.name,a.age,a.mid,a.grade)

imageimageimage

class SchoolPerson:
  def __init__(self,name,age,sex,mid):
    self.name=name
    self.age=age
    self.sex=sex
    self.mid=mid
  def study(self):
    print("it's time to study")

class Student(SchoolPerson):#继承的方法
  def __init__(self,name,age,sex,mid,grade):
    super(Student,self).__init__(name,age,sex,mid)
    self.grade=grade
  def study(self):
    print("i am student,i want to study")

a=Student('A',18,'m','001',1)
a.study()

--------------------------
结果:
i am student,i want to study

多态:

image

class Animal:
  def __init__(self, name): 
    self.name = name
  def talk(self): 
    pass 
  @staticmethod ####如果硬要说多态,建议使用静态方法来处理,而非普通函数
  def animal_talk(obj):
    obj.talk()
class Cat(Animal):
  def talk(self):
    print('喵!')
class Dog(Animal):
  def talk(self):
    print('wang')

d = Dog("小黑")
c = Cat("小白")

# def animal_talk(obj):
#   obj.talk()  ###这也是一个能实现功能的函数,因此python多态才具有争议性

Animal.animal_talk(c)
Animal.animal_talk(d)

希望本文所述对大家Python程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论