赞
踩
魔法函数:在Python中,魔法函数是以__
开头和结尾的函数,例如下面Python中会内置很多的魔法函数
魔法函数是Python的一种高级语法,允许你在类中自定义函数,并绑定到类的特殊方法中。我们经常使用的构造函数__init__
和析构函数__del__
就属于魔法函数
魔法函数作用:类中的魔法函数继承自object
类,其作用有点像Java中的重写(例如Java中我们经常会重写toString
()方法)。接下来举两个例子帮助大家理解魔法函数的作用——让类具有一些额外的功能、方便使用者理解
①:如下有一个CompanyPeople
类,用于描述一个公司的员工,构造函数参数处传入一个参数列表。接着实例化对象company_people
company_people.company_people_list
,而不能直接是company_people
class CompanyPeople():
def __init__(self, company_people_list):
self.company_people_list = company_people_list
company_people = CompanyPeople(["张三", "李四", "王麻子"])
for people in company_people.company_people_list:
print(people)
所以为了让这种遍历显得更加直接,我们可以使用类中的一个魔法函数__getitem__
,它会在对象被迭代时发挥作用。在被迭代时会传入当前的循环变量然后进行索引
company_people
class CompanyPeople():
def __init__(self, company_people_list):
self.company_people_list = company_people_list
def __getitem__(self, item):
return self.company_people_list[item]
company_people = CompanyPeople(["张三", "李四", "王麻子"])
for people in company_people:
print(people)
②:如下是一个People
类,有age
和salary
两个属性,分别表示年龄和薪资。现在我们想要让一些人进行排序,排序就会涉及大小比较,而在正常情况下,人是不能直接比较大小的,所以必须要为其制定一定的规则。这时__gt__
魔法函数就派上用场了,它表示greater than
,所以在进行比较时,该函数就会自动被调用
class People(): def __init__(self, age, salary): self.age = age self.salary = salary def __gt__(self, other): if self.age > other.age: return True else: if self.salary > other.salary: return True else: return False people_list = [People(7, 50000) , People(27, 1300) , People(18, 898989) , People(18, 4000) , People(77, 23000) ] people_list = sorted(people_list) for i in people_list: print(i.age, i.salary)
Python中的魔法函数非常多,仅靠一篇文章不可能全部介绍完毕,而且很多魔法函数必须结合具体的例子学起来才有意义。所以这里重点介绍字符串表示和集合序列相关魔法函数,剩余魔法函数在大家遇到此类问题时随时查阅学习即可
①:__repr__
:用于自定义输出实例化对象信息
__repr__
方法时)会得到“类名+object at+内存地址”这样格式的信息__repr__
方法时,解释器会按照你所定义的格式输出实例对象信息__repr__
面向程序员lass People1(): pass people1 = People1() print(people1) # 相当于执行了print(people1.repr()) print("-"*20) class People2(): def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return "People2[name=" + self.name + ", age=" + str(self.age) + "]" people2 = People2("张三", 27) print(people2)
②:__str__
:用于返回一个对象的描述信息
__str__
面向用户__repr__
适用于所有环境中,__str__
只是覆盖了__repr__
以得到更友好的用户显示toString()
方法
class People():
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "name:%s, age:%d" % (self.name, self.age)
#或者
return "name=" + self.name + ", age=" + str(self.age)
people = People("张三", 27)
print(people)
①:__len__
:在Python中,我们经常会使用len()
函数获取一个对象的长度,实际上在其内部会自动调用该对象的__len()__
方法
class WordNums():
def __init__(self, *args):
self.word = args
def __len__(self):
print("调用了__len__方法")
return len(self.word)
ret = WordNums('hello', 'world', 'Python', 'encoding')
print(len(ret))
②:__getitem__
:在被迭代时会传入当前的循环变量然后进行索引
class CompanyPeople():
def __init__(self, company_people_list):
self.company_people_list = company_people_list
def __getitem__(self, item):
return self.company_people_list[item]
company_people = CompanyPeople(["张三", "李四", "王麻子"])
for people in company_people:
print(people)
print(company_people[1])
③:__ setitem__
: 这个方法应该以与键相关联的方式(类似字典的方式)存储值,以便之后能够使用__setitem__来获取(也即key/value
)
class Test: def __init__(self): self.dicts = {'a':'A', 'b':'B', 'c':'D'} def __getitem__(self, item): return self.dicts[item] def __setitem__(self, key, value): print("调用__setitem") self.dicts[key] = value test = Test(); print("test[a]=" + test['a']) print("test[b]=" + test['b']) print("test[c]=" + test['c']) print("-"*20) test['c'] = 'C' print("test[c]=" + test['c'])
④:__ delitem__
: 此方法在对象组成部分(对象必须可变)使用del
语句时被调用,会删除与key
相关联的值
class Test: def __init__(self): self.dicts = {'a':'A', 'b':'B', 'c':'D'} def __getitem__(self, item): return self.dicts[item] def __setitem__(self, key, value): print("调用__setitem") self.dicts[key] = value def __delitem__(self, key): print("调用__delitem") del self.dicts[key] test = Test(); print(test.dicts) print("-"*20) del test['c'] print(test.dicts)
⑤:__ contains__
: 用于判断我们输入的数据是否在类里
class Test:
def __init__(self):
self.lists = [111, 222, 333, 999]
def __getitem__(self, item):
return self.lists[item]
def __contains__(self, item):
return item in self.lists
test = Test()
print(test.lists)
print(444 in test.lists)
print(999 in test.lists)
__iter__
__next__
_call_
__enter__
__exit__
__abs__
__bool__
__int__
__float__
__hash__
__index__
__new__
__init__
__getattr__
、__setattr__
__getattribute__
、__setattribute__
__dir__
__get__
__set__
__delete__
__await__
__aiter__
__anext__
__aenter__
__aexit__
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。