将python所有魔术方法以实例的方法进行展示
# 代码
import math
class MyClass:
def __new__(cls, *args, **kwargs):
"""创建对象,需要返回一个本类型的实例作为__init__的第一个参数"""
print('__new__')
return super().__new__(cls)
def __init__(self, *args, **kwargs):
"""初始化对象"""
print('__init__')
self.name = kwargs.get('name', 'rico')
self.num = kwargs.get('num', 0)
def __call__(self, *args, **kwargs):
print('called')
def __format__(self, format_spec):
"""当对象使用format函数的时候还调用该方法"""
print('__format__')
if format_spec == 'f':
return str(float(self.num))
else:
return str(self.num)
def __str__(self):
"""此方法返回一个字符串,该字符串是对象数据的字符串表示形式,在打印时调用"""
print('__str__')
return r'{0},{1}'.format(self.name, self.num)
def __repr__(self):
"""此方法类似于__str__方法,但其用途略有不同,它会返回一个字符串,
该字符串为对象在python代码中的规范表示形式"""
print('__repr__')
return r'{0},{1}'.format(self.name, self.num)
def __hash__(self):
"""当对象使用hash函数时会调用此函数"""
print('__hash__')
return hash(self.num)
def __bool__(self):
"""布尔转换方法。当对象作为控制结构(例如while或if)中的条件语句出现时,会隐士调用该方法"""
print('__bool__')
return bool(self.num)
def __eq__(self, other):
"""等于测试方法,=="""
print('__eq__')
return self.num == other.num
def __ne__(self, other):
"""不相等测试方法,!="""
print('__ne__')
return self.num != other.num
def __gt__(self, other):
"""大于测试方法,>"""
print('__gt__')
return self.num > other.num
def __lt__(self, other):
"""小于测试方法,<"""
print('__lt__')
return self.num < other.num
def __ge__(self, other):
"""大于等于测试方法,>="""
print('__ge__')
return self.num >= other.num
def __le__(self, other):
"""小于等于测试方法, <="""
print('__le__')
return self.num <= other.num
def __add__(self, other):
"""加法 +"""
print('__add__')
return self.num + other.num
def __sub__(self, other):
"""减法,-"""
print('__sub__')
return self.num - other.num
def __mul__(self, other):
"""乘法,*"""
print('__mul__')
return self.num * other.num
def __floordiv__(self, other):
"""向下取整的除法,//"""
print('__floordiv__')
return self.num // other.num
def __truediv__(self, other):
"""普通除法,/"""
print('__truediv__')
return self.num / other.num
def __divmod__(self, other):
"""由divmod函数执行的除法,该函数返回包含两个值的元组:商,余数"""
print('__divmod__')
return divmod(self.num, other.num)
def __pow__(self, power, modulo=None):
"""幂函数"""
print('__pow__')
return self.num ** power
def __pos__(self):
"""一元正号, +,返回值本身,无意义"""
print('__pos__')
return +self.num
def __neg__(self):
"""一元负号,取反"""
print('__neg__')
return -self.num
def __abs__(self):
"""绝对值,abs"""
print("__abs__")
return abs(self.num)
def __inveet__(self):
"""按位取反,invert"""
print("__invert__")
return ~self.num
def __round__(self, n=None):
"""按精度舍入。通过指定精度的格式化函数和round函数调用此方法。
可选参数n指定要保留的小数位数"""
print('__round__')
return round(self.num, n)
def __floor__(self):
"""向下舍入,math.floor"""
print('__floor__')
return math.floor(self.num)
def __ceil__(self):
"""向上舍入,math.ceil"""
print('__ceil__')
return math.ceil(self.num)
def __trunc__(self):
"""截断方法,仅保留整数位,math.trunc"""
print('__trunc__')
return math.trunc(self.num)
def __iadd__(self, other):
"""+=,此方法应返回self"""
print('__iadd__')
self.num += other.num
return self
def __isub__(self, other):
"""-=,此方法应返回self"""
print('__isub__')
self.num -= other.num
return self
def __imul__(self, other):
"""*=,此方法应返回self"""
print('__imul__')
self.num *= other.num
return self
def __itruediv__(self, other):
"""/=,此方法应返回self"""
print('__itruediv__')
self.num /= other.num
return self
def __ifloordiv__(self, other):
"""//=,此方法应返回self"""
print('__ifloordiv__')
self.num //= other.num
return self
def __imod__(self, other):
"""%=,此方法应返回self"""
print('__imod__')
self.num %= other.num
return self
def __ilshift__(self, other):
"""<<=,此方法应返回self"""
print('__ilshift__')
self.num <<= other.num
return self
def __irshift__(self, other):
""">>=,此方法应返回self"""
print('__irshift__')
self.num >>= other.num
return self
def __iand__(self, other):
"""&=,此方法应返回self"""
print('__iand__')
self.num &= other.num
return self
def __ior__(self, other):
"""|=,此方法应返回self"""
print('__ior__')
self.num |= other.num
return self
def __ixor__(self, other):
"""^=,此方法应返回self"""
print('__ixor__')
self.num ^= other.num
return self
def __int__(self):
"""int(x)"""
print('__int__')
return int(self.num)
def __float__(self):
"""float(x)"""
print('__float__')
return float(self.num)
def __complex__(self):
"""complex(x)"""
print('__complex__')
return complex(self.num)
def getName(self):
return self.name
if __name__ == "__main__":
# 验证__new__和__init__
A = MyClass(name='aabb')
print(A.getName())
# 对象表示方法
B = MyClass(num=3)
print('__format__:', format(B, 'f'))
print('__str__:', B)
print('__repr__:', B)
B.num = 4
print('__hash__:', hash(B))
print('__bool__ 4:', bool(B))
print('__bool__ 0:', bool(B))
# 比较方法
A.num = 1
print('__eq__,4,1', B == A)
print('__ne__,4,1', B != A)
print('__lt__,4,1', B < A)
print('__gt__,4,1', B > A)
print('__ge__,4,1', B >= A)
print('__le__,4,1', B <= A)
C = MyClass(num=3)
print('sorted,4,1,3:', sorted([A, B, C]))
# 算数运算符方法
print('__add__,4,3', B + C)
print('__sub__,4,3', B - C)
print('__mul__,4,3', B * C)
print('__floordiv__,4,3', B // C)
print('__truediv__,4,3', B / C)
print('__divmod__,4,3', divmod(B, C))
print('__pow__,4,3', B ** 3)
# 一元算术方法
F = MyClass(num=-3.2)
print('__pos__,-3.2', +F)
print('__neg__,-3.2', -F)
print('__abs__,-3.2', abs(F))
print('__round__,-3.2', round(F, 1))
print('__floor__,-3.2', math.floor(F))
print('__ceil__,-3.2', math.ceil(F))
print('__trunc__,-3.2', math.trunc(F))
# 就地运算符
I = MyClass(num=5)
print('I=',I)
I += C
print('__idd__,3', I)
I -= C
print('__isub__,3', I)
I *= C
print('__imul__,3', I)
I /= C
print('__itruediv__,3', I)
I //= C
print('__ifloordiv__,3', I)
I %= C
print('__imod__,3', I)
I.num = int(I.num)
I <<= C
print('__ilshift__,3', I)
I >>= C
print('__irshift__,3', I)
I &= C
print('__iand__,3', I)
I |= C
print('__ior__,3', I)
I ^= C
print('__ixor__,3', I)
# 转换方法
N = MyClass(12)
print('__int__,12', int(N))
print('__float__,12', float(N))
print('__complex__,12', complex(N))
# 输出
__new__
__init__
aabb
__new__
__init__
__format__
__format__: 3.0
__str__: __str__
rico,3
__repr__: __str__
rico,3
__hash__
__hash__: 4
__bool__
__bool__ 4: True
__bool__
__bool__ 0: True
__eq__
__eq__,4,1 False
__ne__
__ne__,4,1 True
__lt__
__lt__,4,1 False
__gt__
__gt__,4,1 True
__ge__
__ge__,4,1 True
__le__
__le__,4,1 False
__new__
__init__
__lt__
__lt__
__lt__
__lt__
sorted,4,1,3: __repr__
__repr__
__repr__
[aabb,1, rico,3, rico,4]
__add__
__add__,4,3 7
__sub__
__sub__,4,3 1
__mul__
__mul__,4,3 12
__floordiv__
__floordiv__,4,3 1
__truediv__
__truediv__,4,3 1.3333333333333333
__divmod__
__divmod__,4,3 (1, 1)
__pow__
__pow__,4,3 64
__new__
__init__
__pos__
__pos__,-3.2 -3.2
__neg__
__neg__,-3.2 3.2
__abs__
__abs__,-3.2 3.2
__round__
__round__,-3.2 -3.2
__floor__
__floor__,-3.2 -4
__ceil__
__ceil__,-3.2 -3
__trunc__
__trunc__,-3.2 -3
__new__
__init__
I= __str__
rico,5
__iadd__
__idd__,3 __str__
rico,8
__isub__
__isub__,3 __str__
rico,5
__imul__
__imul__,3 __str__
rico,15
__itruediv__
__itruediv__,3 __str__
rico,5.0
__ifloordiv__
__ifloordiv__,3 __str__
rico,1.0
__imod__
__imod__,3 __str__
rico,1.0
__ilshift__
__ilshift__,3 __str__
rico,8
__irshift__
__irshift__,3 __str__
rico,1
__iand__
__iand__,3 __str__
rico,1
__ior__
__ior__,3 __str__
rico,3
__ixor__
__ixor__,3 __str__
rico,0
__new__
__init__
__int__
__int__,12 0
__float__
__float__,12 0.0
__complex__
__complex__,12 0j
进程已结束,退出代码0