今天复习了面向对象编程:
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
#另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
#多重继承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中排前地父类的方法
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __repr__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
if other.__class__ is Vector:
return Vector(self.a + other.a, self.b + other.b)
elif other.__class__ is int:
return Vector(self.a+other,self.b)
def __radd__(self,other):
"""反向算术运算符的重载
__add__运算符重载可以保证V+int的情况下不会报错,但是反过来int+V就会报错,通过反向运算符重载可以解决此问题
"""
if other.__class__ is int or other.__class__ is float:
return Vector(self.a+other,self.b)
else:
raise ValueError("值错误")
def __iadd__(self,other):
"""复合赋值算数运算符的重载
主要用于列表,例如L1+=L2,默认情况下调用__add__,会生成一个新的列表,
当数据过大的时候会影响效率,而此函数可以重载+=,使L2直接增加到L1后面
"""
if other.__class__ is Vector:
return Vector(self.a + other.a, self.b + other.b)
elif other.__class__ is int:
return Vector(self.a+other,self.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
print (v1+5)
print (6+v2)