擅长:python、mysql、java
<p>使用<a href="https://stackoverflow.com/questions/820742/how-to-bestow-string-ness-on-my-class">how to make a 'stringy' class</a>中的提示,我们可以使一个对象与一个字符串相同,但对于一个额外的<code>sub</code>方法:</p>
<pre><code>import re
class Substitutable(str):
def __new__(cls, *args, **kwargs):
newobj = str.__new__(cls, *args, **kwargs)
newobj.sub = lambda fro,to: Substitutable(re.sub(fro, to, newobj))
return newobj
</code></pre>
<p>这允许使用构建器模式,它看起来更好,但只适用于预先确定的替换数量。如果在循环中使用它,就没有必要再创建额外的类了。E、 g</p>
<pre><code>>>> h = Substitutable('horse')
>>> h
'horse'
>>> h.sub('h', 'f')
'forse'
>>> h.sub('h', 'f').sub('f','h')
'horse'
</code></pre>