安12 发表于 2018-7-26 22:22:51

魔法方法

class nstr(str):

    def __init__(self,arg=''):
      self.total=0
      for each in arg:
            self.total+=ord(each)
    def __add__(self,other):
      return self.total+other.total
    def __sub__(self,other):
      return self.total-other,total
    def __mul__(self,other):
      return self.total*other.total
    def __truediv__(self,other):
      return self.total/other.total



>>> a+B
899
>>> a-B
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
    a-B
File "C:/Users/lenovo/AppData/Local/Programs/Python/Python36-32/自定义加减乘除.py", line 10, in __sub__
    return self.total-other,total
TypeError: unsupported operand type(s) for -: 'int' and 'nstr'
>>>

无符号整形 发表于 2018-7-27 07:48:38

def __sub__(self,other):
      return self.total-other,total
你不小心把点打成了逗号。

BngThea 发表于 2018-7-27 08:49:46

other.total
中间打错,打成了逗号
页: [1]
查看完整版本: 魔法方法