您的位置:首页 > 编程语言 > Python开发

python中类的魔术方法

2017-07-30 21:55 405 查看
目的:学习python中class的magic methods,提高编程效率。

环境:ubuntu 16.4 python 3.5.2

在学习class时一定会接触到它的magic methods,比如常用__init__,形式都是前后有双下划线。除了这个必须的,还有其他有用的方法,下面大概的介绍一下。
运算魔术方法:

__add__ 用作 +
__sub__ 用作 -
__mul__ 用作 *
__truediv__用作/
__floordiv__用作//
__mod__用作%
__pow__用作**
__and__用作&
__xor__用作^
__or__用作|
举例说明:
class SpecialString:
def __init__(self, cont):
self.cont = cont

def __truediv__(self, other):
line = '=' * len(other.cont)
return rn.join([self.cont, line, other.cont])

spam = SpecialString('spam')
hello = SpecialString('Helo world!')
print(spam/hello)

# 结果
>>>
spam
============
Hello world!
>>>
x + y 相当于 x.__add__(y), 但是如果x没有__add__方法,且x和y是不同的类,那么就会检查y有没有__radd__,有则表示为y.__radd__(x),没有则出现TypeError,所有的megic methods都有r methods。

比较魔术方法:
__lt__ 用作 <
__le__ 用作 <=

__eq__ 用作 ==
__ne__ 用作 !=
__gt__ 用作 >
__ge__ 用作 >=
如果__ne__不存在,则返回__eq__的方向。
举例说明:
class SpecialString:
def __init__(self, cont):
self.cont = cont

def __gt__(self, other):
for index in range(len(other.cont) + 1):
result = other.cont[:index] + '>' + self.cont
result += '>' + other.cont[index:]
print(result)

spam = SpecialString('spam')
eggs = SpecialString('eggs')
spam > eggs

# result

>>>
>spam>eggs
e>spam>ggs
eg>spam>gs
egg>spam>s
eggs>spam
>>>


类似容器的魔术方法:
__len__用作 len()
__getitem__ 用作进行索引
__setitem__ 用作分配索引
__delitem__ 用作删除索引
__iter__ 用作迭代对象
__contains__用作in
举例说明:
class VagueList:
def __init__(self, cont):
self.cont = cont

def __getitem__(self, index):
return self.cont[index + random.randint(-1, 1)]

def __len__(self):
return random.randint(0, len(self.cont) * 2)

vague_list = VagueList(['A', 'B', 'C', 'D', 'E'])
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])

#result
>>>
2
2
C
D
>>>
参考文档来源:sololearn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class python methods