你能在 Python 的核心类型上猴子补丁方法吗? [英] Can you monkey patch methods on core types in Python?

查看:84
本文介绍了你能在 Python 的核心类型上猴子补丁方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 可以向 Number 类和其他核心类型添加方法以获得如下效果:

Ruby can add methods to the Number class and other core types to get effects like this:

1.should_equal(1)

但似乎 Python 无法做到这一点.这是真的?如果是这样,为什么?和type不能修改有关系吗?

But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that type can't be modified?

更新:与其讨论猴子补丁的不同定义,我只想关注上面的示例.我已经得出结论,正如你们中的一些人所回答的那样,这是不可能的.但我想更详细地解释为什么不能这样做,也许什么特性(如果在 Python 中可用)会允许这样做.

回答你们中的一些人:我可能想要这样做的原因只是美观/可读性.

To answer some of you: The reason I might want to do this is simply aesthetics/readability.

 item.price.should_equal(19.99)

这读起来更像英文,并清楚地表明哪个是测试值,哪个是预期值,应该是:

This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:

should_equal(item.price, 19.99)

这个概念是 Rspec 和其他一些 Ruby 框架的基础.

This concept is what Rspec and some other Ruby frameworks are based on.

推荐答案

这里的 Monkey Patch 到底是什么意思?有几个略有不同的定义.

What exactly do you mean by Monkey Patch here? There are several slightly different definitions.

如果您的意思是您可以在运行时更改类的方法吗?",那么答案肯定是:

If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:

class Foo:
  pass # dummy class

Foo.bar = lambda self: 42

x = Foo()
print x.bar()

如果您的意思是,您能否在运行时更改类的方法并事后更改该类的所有实例?"那么答案也是肯定的.只需稍微更改顺序:

If you mean, "can you change a class's methods at runtime and make all of the instances of that class change after-the-fact?" then the answer is yes as well. Just change the order slightly:

class Foo:
  pass # dummy class

x = Foo()

Foo.bar = lambda self: 42

print x.bar()

但是对于某些内置类,例如 intfloat,您不能这样做.这些类的方法是用 C 实现的,为了使实现更容易和更高效,牺牲了某些抽象.

But you can't do this for certain built-in classes, like int or float. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.

我不太清楚为什么您无论如何都想改变内置数字类的行为.如果你需要改变他们的行为,把他们子类化!!

I'm not really clear on why you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!

这篇关于你能在 Python 的核心类型上猴子补丁方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆