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

python学习之继承和多态

时间:2019-10-06 20:16:17      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:run   dog   child   父类继承   utf-8   parent   nbsp   参数   object   

#!/home/miao/python python3 
# -*- coding: utf-8 -*-



这是关于继承和多态


class Parent(object):
    def __init__(self,name,age):
        self.__name = name
        self.age = age

    def get_name(self):
        print(self.__name)

    def set_name(self,name):
        self.__name = name
    def run(self):
        print(dad running...)

class ChildOne(Parent):
    def run(self):
        print(child running...)
#这里类ChildOne从父类中继承了其中的函数定义,这是自己定义的一种数据类型
#在定义一个ChildOne类型的变量时要重新传入参数
parent = Parent(aa,45)

print(parent.age)

child = ChildOne(bb,23)

print(child.age)

child.get_name()
child.set_name(miao)
child.get_name()


class Dog(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def get_name(self):
        print(self.name)
    def run(self):
        print(dog running...)

dog = Dog(cc,10)

def print1_twice(parent):
    parent.get_name()
    parent.get_name()
#多态性,从父类继承的类型可以直接使用。子类也是父类的类型,
#注意这里传入的是变量  所以我犯了很严重的错误  变量后加了括号  这样就变成了函数  @实属不该
print1_twice(child)
#print1_twice(parent())  类似于这样
#鸭子类型当类型相似,即都拥有get_name()即为相似的走路姿势,只要有get_name()这个函数就被看作是 鸭子, 姿势像鸭子就是鸭子
#print1_twice(dog())

 

python学习之继承和多态

标签:run   dog   child   父类继承   utf-8   parent   nbsp   参数   object   

原文地址:https://www.cnblogs.com/miaorn/p/11628067.html

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