简体   繁体   中英

Prevent a function from becoming an instancemethod in Python 2

I'm writing some code that works in Python 3 but not Python 2.

foo = lambda x: x + "stuff"

class MyClass(ParentClass):
    bar = foo

    def mymethod(self):
        return self.bar(self._private_stuff)

I would want it to simply print the private stuff, but if I try to run mymethod, I get:

TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got str instance instead)

Of course, the above is not the actual code, but a simplification of the real thing. I wanted to do it like this because I need to pass along private information that I don't want to expose the final user to ie anybody that extends my classes. But in Python 2, the global level lambda (or any plain function) become an instancemethod , which is unwanted in this case!

What do you recommend me to make this piece of code portable?

Simplest:

class MyClass(ParentClass):
    bar = staticmethod(foo)

with the rest of your code staying the same. While staticmethod is most often used as a "decorator", there is no requirement to do so (thus, no requirement for a further level of indirection to have bar be a decorated method calling foo ).

I would go with Alex Martelli's suggestion. Just for the record, though, (I wrote this answer before seeing Alex Martelli's beautiful answer) you can also do the following in Python 2.7 and 3.x (note especially the documentation links I have provided, so that you understand what is going on):

You can use a static method , which will not expect an implicit first argument. Note that lambda expressions cannot take statements , so you will not be able to use the print statement in your lambda function in 2.x.

foo = lambda x: x            # note that you cannot use print here in 2.x

class MyClass(object):

    @staticmethod            # use a static method
    def bar(x):
        return foo(x)        # or simply print(foo(x))

    def mymethod(self):
        return self.bar(1)

>>> m = MyClass()
>>> m.mymethod()
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM