10

Pythonメソッドを静的とインスタンスの両方で同時に定義できますか?何かのようなもの:

class C(object):
    @staticmethod
    def a(self, arg1):
        if self:
            blah
        blah

両方で呼び出すことができるように:

C.a(arg1)
C().a(arg1)

目的は、2セットのロジックを実行できるようにすることです。インスタンスメソッドとしてアクセスする場合は、インスタンス変数を利用して処理を行います。静的メソッドとしてアクセスする場合は、なしでアクセスできます。

4

4 に答える 4

17
import functools

class static_or_instance(object):
  def __init__(self, func):
    self.func = func

  def __get__(self, instance, owner):
    return functools.partial(self.func, instance)

class C(object):
  @static_or_instance
  def a(self, arg):
    if self is None:
      print "called without self:", arg
    else:
      print "called with self:", arg

C.a(42)
C().a(3)
于 2011-05-05T04:34:08.790 に答える
4

formencodeには、classinstancemethod必要なことを行うデコレータがあります。メソッドには2つの引数が必要です(selfそして、呼び出しコンテキストに応じてclsそのうちの1つが渡される可能性があります)None

から持ち上げたformencode/declarative.py

class classinstancemethod(object):
    """
    Acts like a class method when called from a class, like an
    instance method when called by an instance.  The method should
    take two arguments, 'self' and 'cls'; one of these will be None
    depending on how the method was called.
    """

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, type=None):
        return _methodwrapper(self.func, obj=obj, type=type)

class _methodwrapper(object):

    def __init__(self, func, obj, type):
        self.func = func
        self.obj = obj
        self.type = type

    def __call__(self, *args, **kw):
        assert not kw.has_key('self') and not kw.has_key('cls'), (
            "You cannot use 'self' or 'cls' arguments to a "
            "classinstancemethod")
        return self.func(*((self.obj, self.type) + args), **kw)

    def __repr__(self):
        if self.obj is None:
            return ('<bound class method %s.%s>'
                    % (self.type.__name__, self.func.func_name))
        else:
            return ('<bound method %s.%s of %r>'
                    % (self.type.__name__, self.func.func_name, self.obj))

使用例

class A(object):
    data = 5

    @classinstancemethod
    def print_(self=None, cls=None):
        ctx = self or cls
        print ctx.data


>>> A.print_()
5
>>> a = A()
>>> a.data = 4
>>> a.print_()
4
于 2011-05-05T04:33:08.590 に答える
2

selfいいえ。それができたら、メソッド内で何を意味しますか?

于 2011-05-05T04:20:54.787 に答える
1

selfパラメータをに削除すると、コードが機能しますa()。インスタンスで呼び出すとC().a(arg1)無視されます。

ただし、このメソッドを静的メソッドとインスタンスを受け取るメソッドの両方として機能させる必要があります。あなたはそれを両方の方法で持つことはできません。

于 2011-05-05T04:21:01.533 に答える