Python对象代理问题:描述符和@staticmethod
我正在尝试创建一个代理(包装器)对象,以便修改已实例化对象的行为。包装类的属性被设置为新生成的类(使用Python对象代理问题:描述符和@staticmethod,python,static-methods,proxy-classes,python-descriptors,Python,Static Methods,Proxy Classes,Python Descriptors,我正在尝试创建一个代理(包装器)对象,以便修改已实例化对象的行为。包装类的属性被设置为新生成的类(使用type)以及底层对象的属性,这样做是因为Python\uuuu magic\uuuu方法只有在它们是类的成员时才能正确工作。因此,cls是一个包装类,client是底层对象: def __new__(cls, client, *args, **kwargs): ns = {} for i, attr in inspect.getmembers(client):
type
)以及底层对象的属性,这样做是因为Python\uuuu magic\uuuu方法只有在它们是类的成员时才能正确工作。因此,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
传递给它。我尝试过使用\uuuu get\uuuu
,但没有成功。下面是一个失败的最小示例:
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
而不是调用描述符机制的
getattr
。getattr\u static可以这样使用:
A.static = inspect.getattr_static(SuperA, "static")