函数的重写:
将函数重写一遍,如:
class Animal(object):
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
ani = Animal("大黄", 5, 60, 25)
print(ani)
>>> <__main__.Animal object at 0x0000011284C98438>
class Animal(object):
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def __str__(self):
return "%s-%d-%d-%d"%(self.name, self.age, self.height, self.weight)
ani = Animal("大黄", 5, 60, 25)
print(ani) #在打印ani时自动调用str函数
>>>大黄-5-60-25
使用时机:当一个对象的属性值很多,并且都需要打印,重写__str__方法后,简化了代码,方便查看
运算符重载:
类可以重载加减运算,打印,函数调用,索引等内置运算,运算符重载使我们的对象的行为与内置函数一样,在python调用时操作符会自动的作用于类的对象,python会自动的搜索并调用对象中指定的方法完成操作。
#数字和字符串都能直接相加
print(1 + 2)
print("1" + "2")
两个对象不能直接相加,但是使用运算符重载和方法重写就可以了:
class Person(object):
def __init__(self, num):
self.num = num
#运算符重载
def __add__(self, other):
return Person(self.num + other.num)
#方法重写
def __str__(self):
return str(self.num)
per1 = Person(1)
per2 = Person(2)
print(per1 + per2)
>>>3