了解python中的类。我想要两个字符串之间的区别,一种减法。例如:“减去”字符串,python中的类
a = "abcdef"
b ="abcde"
c = a - b
这会给出输出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
,这将在下面的方式工作:
>>> a = MyStr('thethethethethe')
>>> b = a - 'the'
>>> a
'thethethethethe'
>>> b
'thethethethe'
>>> b = a - 2 * 'the'
>>> b
'thethethe'
所以字符串传递给类构造函数被调用__init__
。这运行构造函数并返回一个对象,其中包含字符串的值?然后创建一个新的减法函数,这样当你用MyStr对象使用-
时,它只是定义了减法如何与该类一起工作?当用字符串调用sub时,count用于检查该字符串是否是所创建对象的子字符串。如果是这种情况,则传递的字符串的第一次出现将被删除。这种理解是否正确?
编辑:基本上这个类可以简化为:
class MyStr(str):
def __sub__(self, other):
return self.replace(other, '', 1)
注意:您不需要定义''__init__''如果你没有做其他任何事情比调用超级类。 – hivert
你的理解是正确的,但是请注意,“a - ”“* 2”不会给出与“(a - ”)相同的结果。事实上,第二个会产生一个错误。 – RoadieRich
@RoadieRich为什么会给出错误? – Paul