python - 方法可以用作静态方法还是实例方法?

标签 python static-methods descriptor instance-methods

我希望能够做到这一点:

class A(object):
    @staticandinstancemethod
    def B(self=None, x, y):
        print self is None and "static" or "instance"

A.B(1,2)
A().B(1,2)

这似乎是一个应该有简单解决方案的问题,但我想不出也找不到。

最佳答案

这是可能的,但请不要。不过,我还是忍不住实现了它:

class staticandinstancemethod(object):
     def __init__(self, f):
          self.f = f

     def __get__(self, obj, klass=None):
          def newfunc(*args, **kw):
               return self.f(obj, *args, **kw)
          return newfunc

...及其用途:

>>> class A(object):
...     @staticandinstancemethod
...     def B(self, x, y):
...         print self is None and "static" or "instance"

>>> A.B(1,2)
static
>>> A().B(1,2)
instance

邪恶!

关于python - 方法可以用作静态方法还是实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5812537/

相关文章:

python - 为什么这种方式获取http客户端失败呢?

python - 如何使用部分方法访问类的属性?

python - 如何在pygame中高效地绘制单个像素?

python - 服务器正在运行,但无法在浏览器中打开

python - 如何重新实现 QGraphicsPixmapItem 的 itemChange 和 mouseMoveEvent?

Excel vba 创建范围的所有可能组合

language-agnostic - 使用大量静态方法是一件坏事吗?

Java无名静态方法

python、__slots__ 和 "attribute is read-only"

c++ - const char* 到 TDesC16