重命名内置的python方法,如replace()

时间:2014-09-16 00:29:44

标签: python replace module

我正在编写一个使用string.replace()方法的python脚本。我知道如果我从模块导入python方法,我可以使用from更改其名称,如下所示:

from time import sleep as x

然后,x(5)time.sleep(5)相同。但是我该怎么做到replace()函数呢?它不是来自任何外部模块,我试图这样做:

x = replace()

但它不起作用。它说NameError: name 'replace' is not defined

所以请告诉我如何重命名"内置替换功能。

3 个答案:

答案 0 :(得分:5)

首先,你几乎不应该使用string.replace。正如文档所说:

  

以下函数列表也定义为字符串和Unicode对象的方法;有关这些内容的更多信息,请参阅字符串方法部分。您应该将这些函数视为已弃用...

其次,由于两个不同的原因,这是错误的:

x = replace()

首先,没有名为replace的内置,并且模块中也没有名为replace的全局。如果您执行了from string import *from string import replace,那么您就不会收到此错误 - 但如果您这样做,则可以执行from string import replace as x,就像您已经为time.sleep做的那样{1}}。

其次,这些括号表示您正在调用该函数,并将其返回值分配给x,而不是将函数本身用作值。


所以,我认为你想要的是这个:

x = str.replace

正在访问replace个对象的str方法,并将其存储在x中。像这样的“未绑定方法”可以通过传递str的实例(即任何普通字符串)作为第一个参数来调用。所以:

x(my_string, ' ', '_')

如果你想在x类本身上添加名称str作为方法,你想要的是“monkeypatching”,通常,它很简单:

str.x = str.replace

不幸的是,它不适用于大多数内置类型,至少在CPython中是这样;你会收到这样的错误:

TypeError: can't set attributes of built-in/extension type 'str'

你当然可以创建自己的str子类,并在整个地方使用它而不是str ...但这对字符串文字,从其他函数返回的字符串没有帮助等等,除非你明确地包装它们。而且我不确定这是值得的。但如果你想:

class s(str):
    x = str.replace

现在你可以这样做:

z = s(function_returning_a_string())
z = z.x(' ', '_')

但请注意,最后,z又回归str而不是s,所以如果你想继续使用x,你必须这样做:

z = s(z.x(' ', '_'))

......而且在某个时刻,即使你节省了几次击键,你也无法节省足够的可读性和惯用性。

答案 1 :(得分:0)

你可以做你想做的事情:

a = 'asdf'

a_replace = a.replace

现在a_replace是一个绑定的方法对象,在您调用a.replace(whatever)时会a_replace(whatever)。你也可以

my_replace = str.replace

my_replace('asdf', 'a', 'f') # calls 'asdf'.replace('a', 'f')

然而,你可能想要的是

some_magic()
'asdf'.my_replace('a', 'f') # calls 'asdf'.replace('a', 'f')

如果不搞乱那些你真的不应该搞砸的事情,这是不可能的:

# Awful hack. Last resort only.
import gc
for referrer in gc.get_referrers(str.replace):
    if type(referrer) is dict and str.__dict__ in gc.get_referrers(referrer):
        # Almost certainly the dict behind str's dictproxy.
        referrer['my_replace'] = str.replace
        break

答案 2 :(得分:0)

在您的任何项目中绝对不建议这样做。但这是可能的: 我们可以做一些元黑客 - 用我们的自定义 str 替换内置 str

class myStr(str):
    def def my_replace(self, __old, __new, __count):
        return self.replace(__old, __new, __count)

__builtins__.__dict__['str'] = myStr

现在 str 的所有用法都替换为我们的实现。您可以添加或更改任何您想要的内容。在我们的例子中,两种 replace 方法都可以工作,一种是从 str 继承的,一种是由我们创建的:

print('dsadas'.replace('d', '_'))
>>> _sa_as
print('dsadas'.my_replace('d', '_'))
>>> _sa_as

但请记住,这很有趣,但在实际项目中使用这些技术可能会破坏许多其他功能。