Python手记(三):类的继承

Python手记(三):类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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.子类可以是从某个父类中继承一个构造函数,这个继承的父类一定要写在第一位,后面的继承的父类可以无需拥有构造函数

赏一瓶快乐回宅水吧~
-------------本文结束感谢您的阅读-------------