内置函数---特定算术的运算__add__、__radd__、__iadd__等

内置函数

  • 构造和析构

    __init__ 、 __del__
    
  • 属性操作

__getattr_  _setattr__   _delattr__
  • 支持字典操作

    __getitem_  _setitem__   _delitem__
    
  • 像函数一样

__call__
  • 打印输出
__str __
  • 对象的字符串表示
 ###    __str__ 打印输出

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        #print/str都会触发该方法
    def  __str__(self):
        print('*****8')
        return "姓名:{},年龄:{}".format(self.name,self.age)
    #通常用来返回对象的字符串表示形式
    #调用repr方法时自动触发
    def __repr__(self):
        return  'Person("{}",{})'.format(self.name,self.age)

p = Person('xiaoming',20)
# print(p)
# s = str(p)
# print(p)
r = repr(p)
print(r,type(r))## <class 'str'>
#执行有效的PYthon字符串
r2 = eval(r)
print(r2,type(r2))#<class '__main__.Person'>
  • 特定算术运算符重
class  Num:
    def  __init__(self,math):
        self.math = math
    def __str__(self):
        return  str(self.math)
    ## 对象出现在 + 号的左边
    def __add__(self, other):
        return  self.math +other

    ## 对象出现在 + 号的右边
    def  __radd__(self, other):
        return  self.math +other
    #+=运算时自动触发,若没有用add
    def  __iadd__(self, other):
       return  Num(self.math + other)
n = Num(12)
# ret = n +10
# ret = 10 + n
n += 50
print(n)
  • 自行测试

    加法:__add__  __radd__   __iadd__
    减法:__sub__  __rsub__   __isub__
    乘法:__mul__  __rmul__    __imul__
    除法:__truediv__   __rtruediv__  __itruediv__
    求余:__mod__  __rmod__  __imod__
    
  • 关系运算

    class Num:
        def __init__(self,a):
            self.a = a
            ##大于
        def  __gt__(self, other):
            return  self.a > other
        #小于
        def   __lt__(self, other):
            return   self.a < other
        #等于 ,  == 会触发,不实现__ne__,!=也会触发该方法
        def  __eq__(self, other):
            return   self.a  == other
        #大于等于
        def   __ge__(self, other):
            return self.a >= other
        #小于等于
        def  __le__(self, other):
            return   self.a  <= other
        #不等于:  !=
        def  __ne__(self, other):
            return   self.a != other
    n = Num(20)
    print(n > 10)
    print(n < 10)
    print(n == 10)
    

猜你喜欢

转载自blog.csdn.net/Mr_791063894/article/details/85105838