基于它的访问位置部分评估Python类方法

dav*_*off 6 python

我在python中基本上有以下内容:

class X(object): pass

class Y(object):
  @classmethod
  def method(cls, x_inst, *args, **kwargs):
    #do some work here that requires an instance of x
    pass
Run Code Online (Sandbox Code Playgroud)

我想要做的是向所有X允许访问的实例添加一个动态属性Y,隐式填充method给定实例的第一个参数.EG我希望以下代码能够完全相同:

# current
x = X()
result = Y.method(x, 1, 2, 3)

# desired
x = X()
x.Y.method(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

我想在几个子类上实现这种行为的方法有几种.我目前所做的是创建一个实际返回的YProxy类,X然后将一些代码放入其中.然而,这似乎相当不优雅且难以维护:

class X(object):
  @property
  def Y(self):
    return YProxy(self)

class Y(object):
  @classmethod
  def method(cls, x_inst, *args, **kwargs):
    #do some work here that requires an instance of x
    pass

class YProxy(object):
  def __init__(self, x_inst):
    self.x_inst = x_inst

  def method(self, *args, **kwargs):
    return Y.method(self.x_inst, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

有没有办法有条件地部分评估对象的类方法?

jsb*_*eno 2

它可以通过描述符对象+包装类来完成,广告明确声明您需要在目标类上以这种方式包装的类。

描述符对象是定义__get__方法的任何对象,当描述符是类的一部分时,它允许自定义属性检索。在这种情况下,我们希望当从实例检索该属性(即“Y”类)时,每当从该类检索方法时,都会将该实例插入到参数列表中。

这要求检索到的属性本身是一个具有自定义属性访问权限的“代理”类,以允许动态包装进行记录。

将所有这些翻译成 Python,我们有:

import types
from functools import partial

class APIWrapper(object):
    def __init__(self, apicls, instance):
        self._apicls = apicls
        self._instance = instance
    def __getattribute__(self, attr):
        apicls = object.__getattribute__(self, "_apicls")
        instance = object.__getattribute__(self,"_instance")
        obj = getattr(apicls, attr)
        if isinstance(obj, types.MethodType):
            return partial(obj,instance)
        return obj


class APIProperty(object):
    def __init__(self, cls):
        self.cls = cls
    def __get__(self, instance, cls):
        return APIWrapper(self.cls, instance)

class Y(object):
    @classmethod
    def method(cls, x, *args):
        print cls, x, args

class X(object):
    Y = APIProperty(Y)

#Example usage: 
x = X()
x.Y.method(1,2,3)
Run Code Online (Sandbox Code Playgroud)

(<class '__main__.Y'> <__main__.X object at 0x18ad090> (1, 2, 3)运行时打印)

但我想你不想写

Y = APIWrapper(Y) 
Run Code Online (Sandbox Code Playgroud)

对于您想要以这种方式包装的每个类。(并在包装类之后定义这些类,以便在解析 X 主体时已经解析 Y)。

这可以通过元类、类装饰器来完成,它们必须为您想要应用方法的每个类进行定义 - 相反,我创建了一个在模块定义末尾调用的函数,您在其中定义你的“X”类 - 这个函数将添加所需的类作为每个定义的类的属性(在我的示例中,我希望该类被标记为“auto_api”属性 - 但适合你自己) - 因此,“auto_api”函数,X和Y类的定义就变成这样了(使用与上面相同的APIProperty和APIWrapper)

def auto_api(api_classes, glob_dict):
    for key, value in glob_dict.items():
        if isinstance(value, type) and hasattr(value, "auto_api"):
            for api_class in api_classes:
                setattr(value, api_class.__name__, APIProperty(api_class))


class X(object):
    auto_api = True

class Y(object):
    @classmethod
    def method(cls, x, *args):
        print cls, x, args

auto_api((Y,), globals())

#Example

x = X()
x.Y.method(1,2,3)
Run Code Online (Sandbox Code Playgroud)