我曾经写过一个代码片段在daniweb这个
from __future__ import print_function
from functools import partial
class mixedmethod(object):
"""This decorator mutates a function defined in a class into a 'mixed' class and instance method.
Usage:
class Spam:
@mixedmethod
def egg(self, cls, *args, **kwargs):
if self is None:
pass # executed if egg was called as a class method (eg. Spam.egg())
else:
pass # executed if egg was called as an instance method (eg. instance.egg())
The decorated methods need 2 implicit arguments: self and cls, the former being None when
there is no instance in the call. This follows the same rule as __get__ methods in python's
descriptor protocol.
"""
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
return partial(self.func, instance, cls)
if __name__ == '__main__':
class Spam(object):
@mixedmethod
def ham(self, cls, *args):
if self is None:
print("Spam.ham() was called as a class method with {0}.".format((self, cls)+ args))
else:
print("Spam.ham() was called as an instance method with {0}.".format((self, cls) + args))
def __repr__(self):
return '<Spam instance>'
egg = Spam()
egg.ham(5)
Spam.ham(5)
我希望我能发现,一个小时前 – Flexo
@Flexo这种想法的唯一缺点是不是真的有用。你也可以用不同的名字编写一个类方法和一个实例方法。通常,客户端代码知道参数是类型还是实例。 – Gribouillis
我使用的是跨语言互操作性。即要在Python代理与其他语言之间建立1:1的行为映射,您必须执行此操作。 – Flexo