2013-07-17 56 views
1

了解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) 
+1

注意:您不需要定义''__init__''如果你没有做其他任何事情比调用超级类。 – hivert

+1

你的理解是正确的,但是请注意,“a - ”“* 2”不会给出与“(a - ”)相同的结果。事实上,第二个会产生一个错误。 – RoadieRich

+0

@RoadieRich为什么会给出错误? – Paul

回答

5

是的,你的理解是完全正确的。

如果Python左侧的操作数存在,Python将调用.__sub__()方法;如果没有,则右侧操作数上相应的.__rsub__()方法也可以挂钩到操作中。

查看emulating numeric types了解Python支持的钩子列表以提供更多算术运算符。

请注意.count()调用是多余的;如果other字符串不存在,则.replace()不会失败;全功能可以简化为:

def __sub__(self, other): 
    return self.replace(other, '', 1) 

反向版本将是:

def __rsub__(self, other): 
    return other.replace(self, '', 1) 
+1

给OP的一个提示:整个'__sub__'函数应该只是:'return self.replace(other,'',1)' –

+0

@JonClements:Added。 –

+0

感谢您的答案,是类似sub的​​rsub,但从右侧或?如果我尝试使用rsub,那么' - '不起作用,因为我认为它没有被用来与蝙蝠一起工作。很酷,班级现在在我的OP中编辑成三行。 – Paul