【问题标题】:Monkey Patching a String Python [duplicate]猴子修补字符串Python [重复]
【发布时间】:2019-03-29 17:47:00
【问题描述】:

我正在做一个 python 项目,下面是我所拥有的:

mystring= 'Hello work'

我想编写一个函数,用m 替换k,如下所示:

def replace_alpha(string):
    return string.replace('k', 'm') # returns Hello worm

我想在string 上使用Monkey Patching,这样我就可以通过以下方式使用它:

string = 'Hello work'
string = string.replace_alpha()
print(string)   # prints Hello worm

代替:

string = replace_alpha(string)

这可能吗?我可以使用带有内置的猴子补丁而不是扩展__builtins__吗?

【问题讨论】:

  • 那不是猴子补丁。 Monkey patching 是从不同的范围修改对象。
  • @hspandher op 表示他不想碰__builtins__

标签: python python-3.6


【解决方案1】:

forbiddenfruit 库是可能的:

from forbiddenfruit import curse

def replace_alpha(string):
    return string.replace('k', 'm')

curse(str, "replace_alpha", replace_alpha)

s = 'Hello work'
print(s.replace_alpha())

【讨论】:

  • 这个库的措辞很漂亮:)
【解决方案2】:

这不可能那么容易。您不能设置不可变 str 实例或内置 str 类的属性。没有这种能力,很难改变他们的行为。但是,您可以将str 子类化:

class PatchStr(str):
  def replace_alpha(self):
    return self.replace('k', 'm')

string = PatchStr('hello work')
string = string.replace_alpha()
string
# 'hello worm'

我认为你不能再靠近了。

【讨论】:

  • string 仍然是 "hello work"
  • @AdamSmith 它(调用该方法的 str 对象)也在 OP 的代码中执行。当然,你必须重新分配返回值。
  • 这不是我理解请求的最终状态的方式。
  • @AdamSmith string 只是一个变量名。该行为是OP所述的行为。原帖中的string = string.replace_alpha() 表明他们不希望改变对象。
猜你喜欢
  • 2012-10-13
  • 2015-03-23
  • 2021-12-20
  • 2016-11-23
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2013-12-26
相关资源
最近更新 更多