![](https://img-blog.csdnimg.cn/20201014180756927.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
Python3中的魔术方法
百无一用生
这个作者很懒,什么都没留下…
展开
-
Python3中用于比较的魔术方法
Python3中用于比较的魔术方法 class Person(object): def __init__(self, name, gender, age, weight): self.name = name self.gender = gender self.age = age self.weight = weight ...原创 2018-12-16 15:32:50 · 328 阅读 · 0 评论 -
Python中一元运算符的魔术方法
一元运算符的魔术方法 class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __pos__(self): # 在对象前加“+”的操作 return self def __neg__(self): # 在对象前加“-”的操作...原创 2018-12-16 16:29:28 · 3215 阅读 · 0 评论 -
二元运算符的魔术方法
二元运算符的魔术方法 class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): # 加法操作 new_coordinate = Coordinate(self.x+other.x, sel...原创 2018-12-16 17:08:40 · 326 阅读 · 0 评论 -
增量赋值运算的魔术方法
增量赋值的运算魔术方法 __iadd__(self,other)魔术方法:在给对象做+=运算的时候会执行的方法。 __isub__(self,other)魔术方法:在给对象做-=运算的时候会执行的方法。 __imul__(self,other)魔术方法:在给对象做*=运算的时候会执行的方法。 idiv(self,other)魔术方法:在给对象做/=运算的时候会执行的方法。(Python2) ...原创 2018-12-16 17:38:00 · 279 阅读 · 0 评论 -
控制属性访问的魔术方法
__ getattr__(self, item)的使用场景 访问一个对象属性的时候,如果属性不存在,就会去执行__getattr__()方法,如果属性存在,就不会调用__getattr__()方法 import logging class Person(object): def __init__(self, name): self.name = name ...原创 2018-12-16 20:23:20 · 170 阅读 · 1 评论 -
创建自己的序列,让其支持容器类型的操作。
创建属于自己的序列 如果想要像操作序列那样,操作某些类型相同的对象,但是原生的对象不支持容器类型的操作。这个时候就需创建自己的序列。 class User(object): def __init__(self, id_list= None): self.id_list = id_list def __repr__(self): # f"User...原创 2018-12-17 23:26:26 · 114 阅读 · 0 评论 -
可调用对象的魔术方法,__call__()方法。
__call__()魔术方法: 原理很简单,应用很广泛,直接上代码 class Coordiate(object): def __init__(self, x= 0, y= 0): self.x = x self.y = y def __call__(self, x, y): # 实现__call__方法后,可以像使用函数或者说像类方法...原创 2018-12-17 23:57:05 · 488 阅读 · 0 评论