您必须在类型上查找方法并手动传递第一个 (self) 参数:
type(Klass).get(Klass, 'arg')
这个问题正是special method names are looked up using this path的原因;如果 Python 不这样做,自定义类本身就不能被散列或表示。
您可以利用这一事实;而不是使用get() 方法,而是使用__getitem__,重载[..] 索引语法,并让Python 为你跳type(ob).methodname(ob, *args):
class Meta(type):
def __getitem__(self, arg):
pass
class Klass(object):
__metaclass__ = Meta
def __getitem__(self, arg):
pass
然后Klass()['arg'] 和Klass['arg'] 按预期工作。
但是,如果您必须让Klass.get() 表现不同(并且查找此内容将被Meta.__getattribute__ 拦截),您必须在您的Klass.get 方法中显式处理它;如果在类上调用它会少一个参数,你可以利用它并返回对类的调用:
_sentinel = object()
class Klass(object):
__metaclass__ = Meta
def get(self, arg=_sentinel):
if arg=_sentinel:
if isinstance(self, Klass):
raise TypeError("get() missing 1 required positional argument: 'arg'")
return type(Klass).get(Klass, self)
# handle the instance case ...
您也可以在模仿方法对象的descriptor 中处理此问题:
class class_and_instance_method(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
if instance is None:
# return the metaclass method, bound to the class
type_ = type(cls)
return getattr(type_, self.func.__name__).__get__(cls, type_)
return self.func.__get__(instance, cls)
并将其用作装饰器:
class Klass(object):
__metaclass__ = Meta
@class_and_instance_method
def get(self, arg):
pass
如果没有要绑定的实例,它会将查找重定向到元类:
>>> class Meta(type):
... def __getattr__(self, name):
... print 'Meta.{} look-up'.format(name)
... return lambda arg: arg
...
>>> class Klass(object):
... __metaclass__ = Meta
... @class_and_instance_method
... def get(self, arg):
... print 'Klass().get() called'
... return 'You requested {}'.format(arg)
...
>>> Klass().get('foo')
Klass().get() called
'You requested foo'
>>> Klass.get('foo')
Meta.get look-up
'foo'
可以在元类中应用装饰器:
class Meta(type):
def __new__(mcls, name, bases, body):
for name, value in body.iteritems():
if name in proxied_methods and callable(value):
body[name] = class_and_instance_method(value)
return super(Meta, mcls).__new__(mcls, name, bases, body)
然后您可以使用此元类向类添加方法,而不必担心委托:
>>> proxied_methods = ('get',)
>>> class Meta(type):
... def __new__(mcls, name, bases, body):
... for name, value in body.iteritems():
... if name in proxied_methods and callable(value):
... body[name] = class_and_instance_method(value)
... return super(Meta, mcls).__new__(mcls, name, bases, body)
... def __getattr__(self, name):
... print 'Meta.{} look-up'.format(name)
... return lambda arg: arg
...
>>> class Klass(object):
... __metaclass__ = Meta
... def get(self, arg):
... print 'Klass().get() called'
... return 'You requested {}'.format(arg)
...
>>> Klass.get('foo')
Meta.get look-up
'foo'
>>> Klass().get('foo')
Klass().get() called
'You requested foo'