5

我希望能够做到这一点:

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)

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

4

4 回答 4

9

这是可能的,但请不要。我忍不住实施它:

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

邪恶的!

于 2011-04-28T02:17:19.980 回答
0

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.

于 2011-04-28T01:48:47.457 回答
0

根据您的说法,这是否符合您的要求?我不确定是否有一种方法可以完全按照您所说的“内置”

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
于 2011-04-28T02:46:19.410 回答
-3

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.

于 2011-04-28T01:48:01.437 回答