且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python中类的魔术方法

更新时间:2022-09-17 20:36:01

目的:学习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__用作|

举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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__的方向。

举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

 举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class VagueList:
    def __init__(self, cont):
        self.cont = cont
         
    def __getitem__(self, index):
        return self.cont[index + random.randint(-11)]
     
    def __len__(self):
        return random.randint(0len(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













本文转自RickyHuL51CTO博客,原文链接:http://blog.51cto.com/rickyh/1952167 ,如需转载请自行联系原作者