方法可以用作静态方法还是实例方法? [英] Can a method be used as either a staticmethod or instance method?

查看:130
本文介绍了方法可以用作静态方法还是实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够做到这一点:

I'd like to be able to do this:

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)

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

This seems like a problem that should have a simple solution, but I can't think of or find one.

推荐答案

可能,但请不要这样做.我还是忍不住实现了:

It is possible, but please don't. I couldn't help but implement it though:

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

邪恶!

这篇关于方法可以用作静态方法还是实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆