码迷,mamicode.com
首页 > 编程语言 > 详细

python中类的魔术方法

时间:2017-07-30 23:54:38      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:python   class   methods   

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


本文出自 “RickyHuL” 博客,请务必保留此出处http://rickyh.blog.51cto.com/10934856/1952167

python中类的魔术方法

标签:python   class   methods   

原文地址:http://rickyh.blog.51cto.com/10934856/1952167

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!