通常,描述符用于类属性,如下所示:
class Owner(object):
attr = Attr()
获取时,Owner.attr称为Attr.__get__(self, instance, owner)whereself = Owner.attr和。instance = Noneowner = Owner
Owner实例化的时间将instance是 的实例Owner。
现在我想将此概念应用于方法参数而不是类属性。
它在实践中的样子(假设 的功能Attr是用给定的字符串包装一个字符串):
class Example(object):
def funct(self, param=Attr('t')):
return param == 'test' # < param calls the descriptor here
e = Example()
e.funct('es') # < is True because 'es' wrapped with 't' becomes 'test'.
访问时param,Attr.__get__(self, instance, owner)将使用self = funct.param, instance = functand调用(尽管拥有和相同owner = funct没有意义,可能是?)。但由于不是一个类,这将不起作用。我怎样才能得到类似工作的东西?ownerinstanceNonefunct
函数上的装饰器将处理参数,所以这可能会增加我认为的解决方案。例如,装饰器必须能够更改包装字符串。