
1. 重载:
overloading:就是将函数重新定义一遍。
1.1 __str__( )和__repr__( )的重载:
格式:
__str__( ):在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法。
__repr__( ):给机器用的,在Python解释器或者在cmd的黑屏终端里面输入,注意在没有str时,且有repr,str = repr,其实本事就是打印类本身想要实现的属性。
举例说明1:
class Person(object):
def __init__(self,name,age,height,weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def __str__(self):
# return "这里是__str__"
return "%s-%d-%d-%d" %(self.name,self.age,self.height,self.weight)
# def __repr__(self):
# # return "这里是__str__"
# return "%s-%d-%d-%d" %(self.name,self.age,self.height,self.weight) per = Person("hanmeimei",,,)
print(per)
print(per.__str__()) # 其实不写入类体重,这里也是可以直接打印的。
# hanmeimei---
# hanmeimei---
优点:当一个对象的属性值很多的时候,兵器都需要打印,重写__str__方法后,简化了代码。
1.2 __add__( ) 的重载
比如我们有这么两个运算
print(1 + 2)
print("1" + "2")
我们知道,返回的结果一个是3,一个是12。前面是一个int类型的数值,后面是一个字符串。也就是说,不同类型的加法会有不同给的解释。
因此我们在类中重新定义一个加法的重载。
格式:
__add__(self,other):sef代表加号前面的对象,other表示加法后面的对象。
举例说明2:
class Person(object):
def __init__(self,num):
self.num = num
# 运算符重载
def __add__(self, other): #self 代表加号前面的对象,other表示加法后面的对象
return Person(self.num + other.num)
def __str__(self):
return "num = " + str(self.num) per1 = Person()
per2 = Person()
print(per1 + per2)
print(per1.__add__(per2))
# num =
1.3 其他重载:
Python当中的重载也不算很多,我下面列举了一个小表格,对Python的重载进行罗列
在很多教材中:重载也叫Python的魔法方法。
小贴士:
help和dir
help可以查询相关的内容解释,dir可以查看目录内的内容。
help("__add__()")
# 用help去查找帮助内容:
# No Python documentation found for '__add__()'.
# Use help() to get the interactive help utility.
# Use help(str) for help on the str class. class Person(object):
def __init__(self,name):
self.name = name per = Person("Tom")
print(dir(per))
# 现实类相关的内容
# ['__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__', 'name']
2. 重写:
overriding:就是一个类当中可以有一个以上的方法具有相同名称。
举例说明1:
class Person(object):
def __init__(self,name,age,height,weight):
self.name = name
self.age = age
self.height = height
self.weight = weight def run(self):
print("run1") def run(self):
print("run2") per = Person("hanmeimei",,,)
per.run()
# 返回值:run2
其实我们发现Python并不需要重载。在C#语言中,重载时两个相同的函数名,且参数类型不一样,类似于:
run(int b)
run(long b)
这种函数时重载的现象。但是python里面的重载其实就是识别最后一个函数的意思。
举例说明2:我们在通过一个类的继承来观察重写,在父类中有一个run方法,子类继承父类,也有一个相同的run方法。我们发现也是最后面那个重写的run2进行加载
class Person(object):
def __init__(self,name,age,height,weight):
self.name = name
self.age = age
self.height = height
self.weight = weight def run(self):
print("run1") class Worker(Person):
def __init__(self,name,age,height,weight):
super(Worker,self).__init__(name,age,height,weight) def run(self):
print("run2") per = Person("hanmeimei",,,)
wor = Worker("Tom",,,)
wor.run()
# 返回值:run2