码迷,mamicode.com
首页 > 编程语言 > 详细

Python类(四)-多态

时间:2018-01-27 00:39:12      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:接口   通过   __name__   body   div   def   icm   studying   ati   

多态即一个接口,多种实现

按照平常直接调用

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

class Student(Person):
    def talk(self):
        print(‘%s is studying‘%self.name)

class Teacher(Person):
    def talk(self):
        print(‘%s is teaching‘%self.name)

if __name__ == ‘__main__‘:
    Student(‘John‘).talk()
    Teacher(‘Jane‘).talk()

通过定义函数来实现多态

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

class Student(Person):
    def talk(self):
        print(‘%s is studying‘%self.name)

class Teacher(Person):
    def talk(self):
        print(‘%s is teaching‘%self.name)

def Person_Talk(n):
    n.talk()

if __name__ == ‘__main__‘:
    s = Student(‘John‘)
    t = Teacher(‘Jane‘)
    Person_Talk(s)
    Person_Talk(t)

 通过父类调用来实现多态

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

    @staticmethod
    def Person_Talk(n):
        n.talk()
    
class Student(Person):
    def talk(self):
        print(‘%s is studying‘%self.name)

class Teacher(Person):
    def talk(self):
        print(‘%s is teaching‘%self.name)

if __name__ == ‘__main__‘:
    s = Student(‘John‘)
    t = Teacher(‘Jane‘)
    Person.Person_Talk(s)
    Person.Person_Talk(t)

 

Python类(四)-多态

标签:接口   通过   __name__   body   div   def   icm   studying   ati   

原文地址:https://www.cnblogs.com/sch01ar/p/8361826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!