在python中学习类.我想要两个字符串之间的区别,一种减法.例如:
a = "abcdef"
b ="abcde"
c = a - b
Run Code Online (Sandbox Code Playgroud)
这将给出输出f.
我正在看这个课程,我是新手,所以想要澄清它是如何工作的.
class MyStr(str):
def __init__(self, val):
return str.__init__(self, val)
def __sub__(self, other):
if self.count(other) > 0:
return self.replace(other, '', 1)
else:
return self
Run Code Online (Sandbox Code Playgroud)
这将按以下方式工作:
>>> a = MyStr('thethethethethe')
>>> b = a - 'the'
>>> a
'thethethethethe'
>>> b
'thethethethe'
>>> b = a - 2 * 'the'
>>> b
'thethethe'
Run Code Online (Sandbox Code Playgroud)
因此,将字符串传递给类并调用构造函数__init__.这运行构造函数并返回一个对象,其中包含字符串的值?然后创建一个新的减法函数,这样当你使用-MyStr对象时,它只是定义了减法如何与该类一起工作?当使用字符串调用sub时,count用于检查该字符串是否是创建的对象的子字符串.如果是这种情况,则会删除第一次出现的传递字符串.这种理解是否正确?
编辑:基本上这个类可以简化为:
class MyStr(str):
def __sub__(self, other):
return self.replace(other, '', 1)
Run Code Online (Sandbox Code Playgroud)
是的,你的理解是完全正确的.
.__sub__()如果存在于左侧操作数上,Python将调用一个方法; 如果没有,.__rsub__()右侧操作数上的相应方法也可以挂钩操作.
请参阅模拟数字类型以获取Python支持的钩子列表,以提供更多算术运算符.
请注意,.count()呼叫是多余的; .replace()如果other字符串不存在,将不会失败; 整个功能可以简化为:
def __sub__(self, other):
return self.replace(other, '', 1)
Run Code Online (Sandbox Code Playgroud)
反向版本将是:
def __rsub__(self, other):
return other.replace(self, '', 1)
Run Code Online (Sandbox Code Playgroud)