算数运算
我們都知道在 Python 中,兩個字符串相加會自動拼接字符串,但遺憾的是兩個字符串相減卻拋出異常。因此,現在我們要求定義一個 Nstr 類,支持字符串的相減操作:A – B,從 A 中去除所有 B 的子字符串
示例如下:
>>> a = Nstr('I love FishC.com!iiiiiiii')>>> b = Nstr('i')>>> a - b'I love FshC.com!'實現:
class Nstr(str):def __sub__(self, other):return self.replace(other, '')定義一個類 Nstr,當該類的實例對象間發生的加、減、乘、除運算時,將該對象的所有字符串的 ASCII 碼之和進行計算
示例如下:
>>> a = Nstr('FishC')>>> b = Nstr('love')>>> a + b899總共有兩種實現方法:
第一種
class Nstr:def __init__(self, arg):if isinstance(arg, str):self.total = 0for each in arg:self.total += ord(each)else:print("輸入有誤")def __add__(self, other):return self.total + other.totaldef __sub__(self, other):return self.total - other.totaldef __mul__(self, other):return self.total*other.totaldef __truediv__(self, other):return self.total/other.total這里告訴我們self的確只是一個表明身份的符號。
第二種:
class Nstr(int):def __new__(cls, arg = 0):if isinstance(arg, str):total = 0for each in arg:total += ord(each)arg = totalreturn int.__new__(cls, arg)繼承int,但是賦予int不具備的新的功能。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
- 上一篇: 定义一个栈(Stack)类,用于模拟一种
- 下一篇: 重写描述符(property)魔法方法时