继承
class firstClass:
def setdata(self, value):
self.data = value
def display(self):
print(self.data)
x = firstClass()
y = firstClass()
x.setdata('aaa')
y.setdata(21)
x.display()
# output: aaa
y.display()
# output:21
x.data = 'hehe'
x.display()
output: hehe
x,y本身没有setdata属性,Python会顺着类的连接搜索,也就是Python的继承,继承在属性点号运算时发生的,只于查找连接对象内的变量名有关。以上代码例子中的x.setdata(‘aaa’)会传入self.data中。因为类会产生多个实例,所以必须经过self参数才能获取正在处理的实例。
重载
class SecondClass(firstClass):
def display(self):
print('Current value = "%s"' % self.data)
z = SecondClass()
z.setdata(43)
z.display()
# output: Current value = "43"
因为SecondClass中的变量display在firstClass中找到,所以SecondClass覆盖了firstClass中的变量display,将这种在书中较低处发生的重新定义取代属性的行为成为重载。
构造函数方法(init)
class ThirdClass(SecondClass):
def __init__(self, value):
self.data = value
def __add__(self, other):
return ThirdClass(self.data + other)
def __str__(self):
return '[ThirdClass: %s]' % self.data
def mul(self, other):
self.data *= other
a = ThirdClass('abc')
a.display()
print(a)
# output:Current value = "abc"
# [ThirdClass: abc]
b = a + 'xyz'
b.display()
print(b)
# output:Current value = "abcxyz"
# [ThirdClass: abcxyz]
a.mul(3)
print(a)
# output:[ThirdClass: abcabcabc]
ThirdClass会继承SecondClass的display方法。ThirdClass在生成调用时会传递一个参数,这是传给__init__构造函数内参数value的,并赋值给self.data。