Object Oriented Programming Understanding-3

23 Operator overloading

23.1 Definitions

   Implement operator operations or function operations between instances with custom rules

23.2 Function:

Let the instance operate like a mathematical expression

Let the instance behave like a built-in object with built-in functions

Make the program concise and easy to read

23.3 Object to string function overloading

          repr(obj) string for the machine to see

          Two functions are used to return strings of objects

repr(obj) returns an expression string representing this object, usually: eval ( repr ( obj )) == obj

str(obj) returns a string to show the string

 

>>>s = ‘I am a progrem’

>>>eval(repr(s)) == s

True

23.3.1 Object to string function overloaded method:

   Overloaded method of repr() function:

          def  __repr__(self):

                 ······

   Overloaded method of str() function:

    def __str__(self):

          ·····

Note: If the object does not have a __str__ method, the result of the repr(obj) function is used instead

Example 1

class MyNumber:

    '''This class is used to define an integer number class to demonstrate str function overloading'''

 

    def __init__(self, value):

        self.value = value

 

n1 = MyNumber(100)

n2 = MyNumber(200)

 

print(repr(n1))

print(str(n2))

Results of the:

<__main__.MyNumber object at 0x7fca98594a58>

<__main__.MyNumber object at 0x7fca98594a90>

Example 2

class MyNumber:

    '''This class is used to define an integer number class to demonstrate str function overloading'''

 

    def __init__(self, value):

        self.value = value

 

    def __repr__(self):

        return 'MyNumber('+repr(self.value)+')' #Access the attributes of the instance

 

The string function is overloaded. If the str function is not overloaded, in fact, str(obj) also calls this function

 
n1 = MyNumber(100)

n2 = MyNumber(200)

 

print(repr(n1))

print(str(n2))

Results of the

MyNumber(100)

MyNumber(200)

 

Example 3

class MyNumber:

    '''This class is used to define an integer number class to demonstrate str function overloading'''

 

    def __init__(self, value):

        self.value = value

 

    def __repr__(self):

        return 'MyNumber('+repr(self.value)+')' #Access the attributes of the instance

 

    def __str__(self):

        return 'integer value('+str(self.value)+')'

 

n1 = MyNumber(100)

n2 = MyNumber(200)

 

print(repr(n1))

print(str(n2))

print(n2)

When str is overloaded, the result printed by print is the printing after overloading of str.

If str is not overloaded call repr overload

 
Results of the

MyNumber(100)

Integer value (200)

Integer value (200)

 

Example 4

If you import the program of Example 3 into interactive mode, you will have the following results

>>> n1 = mynumber.MyNumber(100)

>>> n1

MyNumber(100)

There are two different ways to call a function

 
>>> n2 = mynumber.MyNumber(200)

>>> print(n2)

Integer value (200)

24 Overloading of arithmetic operators

+, __add__

-, __sub__

*, __I have__

/ , __Truediv__

//,__floordiv__

%,__mod__

**       __pow__

24.1 二元运算符重载的格式

def __xxx__(slef,other):

   ·······

注:二元运算符的重载方法的参数列表中只能有两个参数

24.2 重载说明:

运算符重载方法的参数已经有固定的含义,不可改变原有意义

除__call__方法外,其它重载方法的参数个数不可变

 

 

 

 

class MyNumber:

    '''此类用于定义一个整型数字类,用于演示str函数重载'''

 

    def __init__(self, value):

        self.value = value

 

    def __repr__(self):

        return 'MyNumber(' + repr(self.value) + ')'  # 访问实例的属性

 

    def __str__(self):

        return '整型数值('+str(self.value)+')'

    def __add__(self,other):

        n = self.value + other.value

        return MyNumber(n)

 

 


n1 = MyNumber(100)

n2 = MyNumber(200)

 

print(n1.__add__(n2))     #等同于下一行

print(n1 + n2)

 

执行结果:

300

300

 

 

示例2

class MyList:

 

    def __init__(self, vaule):

        '''传入参数可变时,必须用拷贝,这样拿到的数据才为此对象所有,否则只是两个变量绑定到一份数据,

        改变原有数据时将改变对象属性的值,这是不允许的'''

        self.vaule = vaule.copy()

 

    def __add__(self, other):

        lst = self.vaule + other.vaule

        return MyList(lst)

 

    def __str__(self):

        return 'MyList(' + str(self.vaule) + ')'

 

 

 

l1 = MyList([1, 2, 3])

 

l2 = MyList([4, 5, 6])

 

print(l1.__add__(l2))  # MyList([1, 2, 3, 4, 5, 6])

print(l2 + l1)

 

print(    MyList([1, 2, 3]) + MyList([4, 5, 6])   )

执行结果

MyList([1, 2, 3, 4, 5, 6])

MyList([4, 5, 6, 1, 2, 3])

MyList([1, 2, 3, 4, 5, 6])

25 反向算术运算

                                                           #这是代码书写格式

+, __radd__(self,lhs)       #      lhs   + self

-, __rsub__(self,lhs)       #      lhs   - self

*, __rmul__(self,lhs)       #      lhs   * self

/, __rtruediv__(self,lhs)    #      lhs   / self

//, __rfloordiv__(self,lhs)  #      lhs  // self

%, __rmod__(self,lhs)     #      lhs   % self

**  __rpow__(self,lhs)      #      lhs **  self


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325814260&siteId=291194637