算数运算
我們都知道在 Python 中,兩個(gè)字符串相加會(huì)自動(dòng)拼接字符串,但遺憾的是兩個(gè)字符串相減卻拋出異常。因此,現(xiàn)在我們要求定義一個(gè) Nstr 類,支持字符串的相減操作:A – B,從 A 中去除所有 B 的子字符串
示例如下:
>>> a = Nstr('I love FishC.com!iiiiiiii')>>> b = Nstr('i')>>> a - b'I love FshC.com!'實(shí)現(xiàn):
class Nstr(str):def __sub__(self, other):return self.replace(other, '')定義一個(gè)類 Nstr,當(dāng)該類的實(shí)例對(duì)象間發(fā)生的加、減、乘、除運(yùn)算時(shí),將該對(duì)象的所有字符串的 ASCII 碼之和進(jìn)行計(jì)算
示例如下:
>>> a = Nstr('FishC')>>> b = Nstr('love')>>> a + b899總共有兩種實(shí)現(xiàn)方法:
第一種
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的確只是一個(gè)表明身份的符號(hào)。
第二種:
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不具備的新的功能。
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
- 上一篇: 定义一个栈(Stack)类,用于模拟一种
- 下一篇: 重写描述符(property)魔法方法时