摘要:Python魔法函数大全是技术人员必备知识之一,本文将从4个方面对Python魔法函数大全做详细的阐述,为读者提供更多的技术支持。
图片:
一、__call__魔法函数
__call__是一种特殊的函数,当实例作为函数调用时,__call__会被调用。通常用于处理函数对象,常见的应用场景为给一个class增加可调用函数的功能,并且它可以被重载。例如:
class Foo:
def __call__(self):
return "Hello World"
f=Foo()
print(f()) #返回"Hello World"
在这里,__call__函数被定义在class Foo里面,f()作为函数被调用之后,调用的就是__call__函数。
通过__call__魔法函数,我们可以在一个class中增加可调用的函数,极大地简化了代码的编写。
二、__str__和__repr__魔法函数
__str__和__repr__两个魔法函数都是用来返回对象的字符串表示形式的。两者的区别在于:__str__是在使用print函数打印对象时被调用,而__repr__是在使用repr函数打印对象时被调用。
例如:
class Foo:
def __str__(self):
return "This is Foo"
def __repr__(self):
return "Foo()"
f=Foo()
print(f) #返回字符串:"This is Foo"
print(repr(f)) #返回字符串:"Foo()"
通过__str__和__repr__两个函数,我们可以灵活地控制对象在不同情况下的展示方式。
三、__len__魔法函数
__len__函数是用来返回对象的长度的,它可以被重载,用于自定义对象的长度计算方法。例如:
class Foo:
def __init__(self):
self.items=[1,2,3]
def __len__(self):
return len(self.items)
f=Foo()
print(len(f)) #返回3
通过重载__len__函数,我们可以灵活地计算不同类型的对象的长度。
四、__getattr__和__setattr__魔法函数
__getattr__和__setattr__这两个函数都是用来处理对象属性的,其中__getattr__作用于属性获取,而__setattr__作用于属性设置。
例如:
class Foo:
def __getattr__(self,name):
return "The attribute %s is not exist" %name
def __setattr__(self,name,value):
if name=="age" and value>100:
raise ValueError("Invalid value for age")
else:
super().__setattr__(name,value)
f=Foo()
print(f.name) #返回"The attribute name is not exist"
f.age=200 #引发ValueError:"Invalid value for age"
通过__getattr__和__setattr__函数,我们可以自定义属性获取和设置的方式,并在必要时抛出异常。
评论前必须登录!
注册