【问题标题】:Python object proxy problem: descriptors and @staticmethodPython对象代理问题:描述符和@staticmethod
【发布时间】:2019-12-17 07:06:10
【问题描述】:

我正在尝试创建一个代理(包装器)对象,以便我可以修改已实例化对象的行为。包装类的属性与底层对象的属性一起设置为新生成的类(使用type),这样做是因为 Python __magic __ 方法只有在它们是类的成员时才能正常工作。所以cls是一个包装类,client是底层对象:

def __new__(cls, client, *args, **kwargs):
    ns = {}
    for i, attr in inspect.getmembers(client):
        if i in ('__init__', '__new__', '__getattribute__', '__dict__'):
            continue
        ns[i] = attr
    for i in cls.__dict__:
        if i in ('__new__',):
            continue
        elif i == '__init__':
            ns['_init_'] = getattr(cls, i)
            continue
        attr = getattr(cls, i)
        ns[i] = attr
    P = type(cls.__name__ + "." + client.__class__.__name__,
             (Proxy2.BaseProxy,), ns)
    P._client_ = client
    return P(*args, **kwargs)

问题来自包装类中的@staticmethod/@classmethod。我无法从实例调用静态方法,因为 self 正在传递给它。我尝试使用__get__,但没有成功。这是一个失败的最小示例:

class SuperA:
    @staticmethod
    def static():
        return 'static?'

class A:
    def __getattribute__(self, attr):
        v = object.__getattribute__(self, attr)
        if hasattr(v, '__get__'):
            v2 = v.__get__(None, self)
            return v2
        return v

A.static = getattr(SuperA, "static")
print(A.static())  # success
print(A().static())  # fail

【问题讨论】:

    标签: python static-methods proxy-classes python-descriptors


    【解决方案1】:

    可以像这样使用inspect.getattr_static 而不是调用描述符机制的getattr:

    A.static = inspect.getattr_static(SuperA, "static")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 2019-12-03
      相关资源
      最近更新 更多