且构网

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

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

更新时间:2023-12-02 19:42: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).