pytho继承和多态笔记

摘抄自Python-面向对象

一.继承

1.继承有两种写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class a(object):
def method(self, arg):
pass
class b(a):
def method(self, arg):
super(b, self).method(arg)
或者
class a(object):
def method(self, arg):
pass
class b(a):
def method(self, arg):
a.method(arg)

2.继承的代码

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
class Programer(object):
hobby = 'play computer'
def __init__(self, name, age, weight):
self.name = name
self._age = age
self.__weight = weight
@classmethod
def get_hobby(cls):
return cls.hobby
@property
def get_weight(self):
return self.__weight
def self_introduction(self):
print('My name is %s \nI am %s years old\n' % (self.name, self._age))
class BackendProgramer(Programer):
def __init__(self, name, age, weight, language):
super(BackendProgramer, self).__init__(name, age, weight)
self.language = language
if __name__ == '__main__':
programer = BackendProgramer('Albert', 25, 80, 'Python')
print(dir(programer))
print(programer.__dict__)
print(type(programer))
print(isinstance(programer, Programer))

输出

1
2
3
4
['_Programer__weight', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_age', 'get_hobby', 'get_weight', 'hobby', 'language', 'name', 'self_introduction']
{'name': 'Albert', '_age': 25, '_Programer__weight': 80, 'language': 'Python'}
<class '__main__.BackendProgramer'>
True

二.多态

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
class Programer(object):
hobby = 'play computer'
def __init__(self, name, age, weight):
self.name = name
self._age = age
self.__weight = weight
@classmethod
def get_hobby(cls):
return cls.hobby
@property
def get_weight(self):
return self.__weight
def self_introduction(self):
print('My name is %s \nI am %s years old\n' % (self.name, self._age))
class BackendProgramer(Programer):
def __init__(self, name, age, weight, language):
super(BackendProgramer, self).__init__(name, age, weight)
self.language = language
def self_introduction(self):
print('My name is %s \nI am %s years old\n' % (self.name, self.language))
def introduce(programer):
if isinstance(programer, Programer):
programer.self_introduction()
if __name__ == '__main__':
programer = Programer('Albert', 25, 80)
backend_programer = BackendProgramer('Tim', 30, 70, 'Python')
introduce(programer)
introduce(backend_programer)

输出:

1
2
3
4
5
My name is Albert
I am 25 years old
My name is Tim
I am Python years old

  多态可以让它不管调用的是哪个类,只要它是某个类的子类 ,都可以直接调用这个方法