Can a method be used as either a staticmethod or instance method?

柔情痞子 提交于 2019-12-01 18:03:40

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

...and its use:

>>> 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

Evil!

Since you'd like the static method case to be used to create a new class anyway, you'd best just make it a normal method and call it at the end of the __init__ method.

Or, if you don't want that, create a separate factory function outside the class that will instantiate a new, empty object, and call the desired method on it.

There probably are ways of making exactly what you are asking for, but they will wander through the inner mechanisms of Python, be confusing, incompatible across python 2.x and 3.x - and I can't see a real need for it.

From what you're saying, is this along the line of what you're looking for? I'm not sure there is a way to do exactly what you're saying that is "built in"

class Foo(object):
    def __init__(self, a=None, b=None):
        self.a
        self.b

    def Foo(self):
        if self.a is None and self.b is None:
            form = CreationForm()
        else: 
            form = EditingForm()
        return form

The answer to your question is no, you can't do that.

What I would do, since Python also supports regular functions, is define a function outside that class, then call that function from a normal method. The caller can decide what which one is needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!