python magic函数_PythonStudy——魔法函数 Magic Methods

Python的魔法函数(Magic Methods)允许开发者自定义类的行为,如比较、操作符重载等。本文介绍了如何使用`__init__`、`__add__`、`__str__`等魔法函数,并通过示例展示了如何创建一个自定义的向量类,实现加法操作和字符串表示。此外,还列举了常见的魔法函数及其用途,包括构造、比较、一元和二元操作符等。
摘要由CSDN通过智能技术生成

魔法函数

python中以双下划线开始和结束的函数(不可自己定义)为魔法函数

调用类实例化的对象的方法时自动调用魔法函数(感觉不需要显示调用的函数都叫)

在自己定义的类中,可以实现之前的内置函数,比如下面比较元素sorted时用It函数(lt(self, other):判断self对象是否小于other对象;)

48304ba5e6f9fe08f3fa1abda7d326ab.png

class MyVector(object):

def __init__(self, x, y):

self.x = x

self.y = y

def __add__(self, other_instance):

re_vector = MyVector(self.x+other_instance.x, self.y+other_instance.y)

return re_vector

def __str__(self):

return"x:{x}, y:{y}".format(x=self.x, y=self.y)

first_vec = MyVector(1,2)

second_vec = MyVector(2,3)

print(first_vec+second_vec)

48304ba5e6f9fe08f3fa1abda7d326ab.png

操作符重载:通过定义类的一些约定的以"__"开头并结尾的函数,可以到达重载一些特定操作的目的

__str__ / __unicode__

当print一个对象实例时,实际是print该实例 .str()函数的返回值:

class A:

def __str__(self):

return "A"

def __unicode__(self):

return "uA"

魔法函数有什么作用?

魔法函数可以为你写的类增加一些额外功能,方便使用者理解。举个简单的例子,我们定义一个“人”的类People,当中有属性姓名name、年龄age。让你需要利用sorted函数对一个People的数组进行排序,排序规则是按照name和age同时排序,即name不同时比较name,相同时比较age。由于People类本身不具有比较功能,所以需要自定义,你可以这么定义People类:

48304ba5e6f9fe08f3fa1abda7d326ab.png

class People(object):

def __init__(self, name, age):

self.name = name

self.age = age

return

def __str__(self):

return self.name + ":" + str(self.age)

def __lt__(self, other):

return self.name < other.name if self.name != other.name else self.age < other.age

if __name__=="__main__":

print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))

48304ba5e6f9fe08f3fa1abda7d326ab.png

上个例子中的__lt__函数即less than函数,即当比较两个People实例时自动调用。

Python中有哪些魔法函数?

Python中每个魔法函数都对应了一个Python内置函数或操作,比如__str__对应str函数,__lt__对应小于号

类的构造、删除:

object.__new__(self, ...)

object.__init__(self, ...)

object.__del__(self)

二元操作符:

+object.__add__(self, other)

-object.__sub__(self, other)

*object.__mul__(self, other)

//object.__floordiv__(self, other)

/object.__div__(self, other)

%object.__mod__(self, other)

**object.__pow__(self, other[, modulo])

<

>>object.__rshift__(self, other)

&object.__and__(self, other)

^object.__xor__(self, other)

|object.__or__(self, other)

扩展二元操作符:

+=object.__iadd__(self, other)

-=object.__isub__(self, other)

*=object.__imul__(self, other)

/=object.__idiv__(self, other)

//=object.__ifloordiv__(self, other)

%=object.__imod__(self, other)

**=object.__ipow__(self, other[, modulo])

<<=object.__ilshift__(self, other)

>>=object.__irshift__(self, other)

&=object.__iand__(self, other)

^=object.__ixor__(self, other)

|=object.__ior__(self, other)

一元操作符:

-object.__neg__(self)

+object.__pos__(self)

abs()object.__abs__(self)

~object.__invert__(self)

complex()object.__complex__(self)

int()object.__int__(self)

long()object.__long__(self)

float()object.__float__(self)

oct()object.__oct__(self)

hex()object.__hex__(self)

round()object.__round__(self, n)

floor()object__floor__(self)

ceil()object.__ceil__(self)

trunc()object.__trunc__(self)

比较函数:

<=object.__le__(self, other)

==object.__eq__(self, other)

!=object.__ne__(self, other)

>=object.__ge__(self, other)

>object.__gt__(self, other)

类的表示、输出:

str()object.__str__(self)

repr()object.__repr__(self)

len()object.__len__(self)

hash()object.__hash__(self)

bool()object.__nonzero__(self)

dir()object.__dir__(self)

sys.getsizeof()object.__sizeof__(self)

类容器:

len()object.__len__(self)

self[key]object.__getitem__(self, key)

self[key] = valueobject.__setitem__(self, key, value)

del[key] object.__delitem__(self, key)

iter()object.__iter__(self)

reversed()object.__reversed__(self)

in操作object.__contains__(self, item)

字典key不存在时object.__missing__(self, key)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值