zoukankan      html  css  js  c++  java
  • Python类(四)-多态

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

    按照平常直接调用

    # -*- 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)
    
  • 相关阅读:
    怎样用wordpress建立一个博客
    TCP三次握手
    抓取动态页面
    Controller的激活
    使用PHPnow搭建本地wordpress
    自己动手从头制作WordPress主题探索add_action和do_action
    Cat in dotNET
    如何在本地搭建Wordpress环境
    Windows7下Emacs的安装
    Windows下Emacs的安装
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8361826.html
Copyright © 2011-2022 走看看