【问题标题】:can a function be static and non-static in python 2python 2中的函数可以是静态的还是非静态的
【发布时间】:2017-11-22 22:23:36
【问题描述】:

假设我有这门课:

class Test(object):
    def __init__(self, a):
        self.a = a

    def test(self, b):
        if isinstance(self, Test):
            return self.a + b
        else:
            return self + b

在我的世界中,理想情况下会这样做:

>>> Test.test(1,2)
3
>>> Test(1).test(2)
3

现在这不起作用,因为您收到此错误:

TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead)

在 python3 中这工作正常,我偷偷怀疑这可以通过 python2 中的装饰器实现,但我的 python foo 不够强大,无法让它工作。

Plot Twist:那么当我需要一些东西而不是静态调用时会发生什么。

【问题讨论】:

  • 哎呀,只需添加 @staticmethod 装饰器就可以了...

标签: python python-2.x


【解决方案1】:

如果您希望在实例上调用时实际接收self,但也可以在类上调用,则建议您编写自己的描述符类型:

import types

class ClassOrInstanceMethod(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def __get__(self, instance, owner):
        if instance is None:
            instance = owner
        return self.wrapped.__get__(instance, owner)

class demo(object):
    @ClassOrInstanceMethod
    def foo(self):
        # self will be the class if this is called on the class
        print(self)

Demo.

对于您问题的原始版本,您可以像使用任何其他静态方法一样编写它,使用@staticmethod。在实例上调用静态方法与在类上调用它的工作方式相同:

class Test(object):
    @staticmethod
    def test(a, b):
        return a + b

Demo.

【讨论】:

  • 但是考虑到可选的self参数。 :)
  • @albertjan:静态方法不会收到隐含的self,即使您在实例上调用它们也是如此。
  • 这正是我想要的完美,MethodType 是否创建了一个新的“绑定”方法?
  • @albertjan:是的。它还可以在 Python 2 上制作未绑定的方法对象; instance = owner 位避免了这种情况。 (另外,我现在更改了创建方法对象的代码,因为types.MethodType 的签名在 Python 3 中发生了变化。这种方式应该与 2 和 3 兼容。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2021-10-18
  • 2011-01-16
  • 2021-10-20
  • 2016-02-16
相关资源
最近更新 更多