Python中的静态和实例方法

xst*_*ter 10 python static-methods descriptor instance-methods

我可以将Python方法同时定义为静态和实例吗?就像是:

class C(object):
    @staticmethod
    def a(self, arg1):
        if self:
            blah
        blah
Run Code Online (Sandbox Code Playgroud)

所以我可以用它们来调用它:

C.a(arg1)
C().a(arg1)
Run Code Online (Sandbox Code Playgroud)

目的是能够运行两组逻辑.如果作为实例方法访问,它将使用实例变量并执行操作.如果作为静态方法访问,它将不会.

Fre*_*urk 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)
Run Code Online (Sandbox Code Playgroud)

  • 很酷.但我讨厌它:D (4认同)