簡體   English   中英

方法可以用作靜態方法或實例方法嗎?

[英]Can a method be used as either a staticmethod or instance method?

我希望能夠做到這一點:

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

邪惡的!

因為無論如何您都希望使用 static 方法案例來創建新的 class,所以您最好將其設為普通方法並在__init__方法的末尾調用它。

或者,如果您不希望這樣做,請在 class 之外創建一個單獨的工廠 function,該工廠將實例化一個新的空 object,並在其上調用所需的方法。

可能有一些方法可以完全滿足您的要求,但它們會在 Python 的內部機制中徘徊,令人困惑,在 python 2.x 和 3.x 之間不兼容 - 我看不出真正需要它。

根據您的說法,這是否符合您的要求? 我不確定是否有一種方法可以完全按照您所說的“內置”

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

你的問題的答案是否定的,你不能那樣做。

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. 調用者可以決定需要哪一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM