Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
防止函数成为Python 2中的instancemethod_Python_Python 3.x_Portability_Python 2.x - Fatal编程技术网

防止函数成为Python 2中的instancemethod

防止函数成为Python 2中的instancemethod,python,python-3.x,portability,python-2.x,Python,Python 3.x,Portability,Python 2.x,我正在编写一些在Python3中工作但在Python2中不工作的代码 foo = lambda x: x + "stuff" class MyClass(ParentClass): bar = foo def mymethod(self): return self.bar(self._private_stuff) 我希望它只打印私有内容,但如果我尝试运行mymethod,我会得到: TypeError: unbound method <lambda&g

我正在编写一些在Python3中工作但在Python2中不工作的代码

foo = lambda x: x + "stuff"

class MyClass(ParentClass):
    bar = foo

    def mymethod(self):
        return self.bar(self._private_stuff)
我希望它只打印私有内容,但如果我尝试运行mymethod,我会得到:

TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got str instance instead)
TypeError:必须使用MyClass实例作为第一个参数调用unbound方法()(改为使用Get-str实例)
当然,上面的代码不是实际的代码,而是对实际情况的简化。我想这样做是因为我需要传递私人信息,我不想将最终用户暴露给任何扩展我的类的人。但是在Python2中,全局级别的lambda(或任何普通函数)变成了
instancemethod
,在本例中这是不需要的


您建议我如何使这段代码可移植?

我同意Alex Martelli的建议。不过,为了记录在案,(在看到Alex Martelli漂亮的答案之前,我写了这个答案),您还可以在Python 2.7和3.x中执行以下操作(请特别注意我提供的文档链接,以便您了解发生了什么):

您可以使用,它不需要隐式的第一个参数。请注意,因此您将无法在2.x中的
lambda
函数中使用
print
语句

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
最简单的:

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

代码的其余部分保持不变。虽然
staticmethod
最常被用作“装饰器”,但不需要这样做(因此,不需要进一步的间接层次将
bar
作为调用
foo
的装饰方法)。

必须指出:如果有人可以扩展您的类,你不能对他们保密。我不想让其他人知道如何做自己的事。如果他们愿意,他们可以。但这就是我写这篇文章的原因,所以他们不需要。我不知道它在Py3中如何工作。这里的情况几乎相同,只是我得到了一条不同的消息:
TypeError:()接受1个位置参数,但给出了2个
——而Py2给了我几乎相同的消息
TypeError:()正好接受1个参数(给出了2个)
。对了!我的不好,但无论如何这是有用的。更新了我的问题以反映这一点。