且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 python 类的任何实例上模拟方法

更新时间:2023-12-02 20:03:34

最简单的方法可能是使用类方法.您确实应该使用实例方法,但创建这些方法很痛苦,而有一个内置函数可以创建类方法.使用类方法,您的存根将获得对类(而不是实例)的引用作为第一个参数,但由于它是一个存根,这可能无关紧要.所以:

Easiest way is probably to use a class method. You really should use an instance method, but it's a pain to create those, whereas there's a built-in function that creates a class method. With a class method, your stub will get a reference to the class (rather than the instance) as the first argument, but since it's a stub this probably doesn't matter. So:

Product.name = classmethod(lambda cls: "stubbed_name")

请注意,lambda 的签名必须与您要替换的方法的签名相匹配.此外,当然,由于 Python(如 Ruby)是一种动态语言,因此不能保证在您接触实例之前不会有人将您的存根方法切换为其他东西,尽管我希望您很快就会知道如果发生这种情况.

Note that the signature of the lambda must match the signature of the method you're replacing. Also, of course, since Python (like Ruby) is a dynamic language, there is no guarantee that someone won't switch out your stubbed method for something else before you get your hands on the instance, though I expect you will know pretty quickly if that happens.

在进一步调查中,您可以省略classmethod():

On further investigation, you can leave out the classmethod():

Product.name = lambda self: "stubbed_name"

我试图尽可能地保留原始方法的行为,但看起来实际上并没有必要(无论如何,并没有像我希望的那样保留行为).

I was trying to preserve the original method's behavior as closely as possible, but it looks like it's not actually necessary (and doesn't preserve the behavior as I'd hoped, anyhow).