前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中类的魔术方法

python中类的魔术方法

作者头像
py3study
发布2020-01-09 15:49:56
8660
发布2020-01-09 15:49:56
举报
文章被收录于专栏:python3python3

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

举例说明:

代码语言:javascript
复制
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__的方向。

举例说明:

代码语言:javascript
复制
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

 举例说明:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档