Python手记(三):类的继承

Python手记(三):类的继承

#Author :ywq
class human:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def think(self):
        print('Human %s is thinking about something ' %self.name)
    def talk(self):
        print('Human %s is talking with others' % self.name)

class animals:
    def eat(self):
        print('animal %s need to eat for survival' % self.name)


class man(human,animals):
    def __init__(self,name,age,money):
        self.name=name
        self.age=age
        self.money=money
    def fighting(self):
        print('Man should fighting for a family')

class woman(human,animals):
    def born(self):
        print('woman can reproduction')
    def talk(self,obj):
        super(woman,self).talk()
        print('woman %s is talking with %s' % (self.name,obj.name))


a=man("Alex",22,100)
a.fighting()
a.think()
a.talk()
a.eat()

b=woman('Alice',20)
b.born()
b.eat()
b.talk(a)


#######
>>>Man should fighting for a family
>>>Human Alex is thinking about something 
>>>Human Alex is talking with others
>>>animal Alex need to eat for survival
>>>woman can reproduction
>>>animal Alice need to eat for survival
>>>Human Alice is talking with others
>>>woman Alice is talking with Alex

结论:

1.在父类(human)和子类(man)都定义了构造函数时(其他函数类同),以子类本身优先级最高,所以需要按照子类中构造函数的的标准提供3个变量(name.age,money);

2.若子类的函数与父类同名,则优先只运行子类,若希望与父类一起运行,则可在子类函数内使用super(SUBCLASS_NAME,self),FUNC_NAME()方式调用父类函数,两者一起运行;

3.如果子类没有定义构造函数,可以直接继承调用父类的构造函数,方法等;

4.如果继承的父类有多个时,按从左至右的顺序装配,优先级左边最高;

5.基类必须要有构造函数才能运行,且类的实例的变量数要与构造函数参数一一对应;

6.子类可以是从某个父类中继承一个构造函数,这个继承的父类一定要写在第一位,后面的继承的父类可以无需拥有构造函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值