質問

Normally a descriptor is used on a class attribute like so:

class Owner(object):
    attr = Attr()

When getting Owner.attr, Attr.__get__(self, instance, owner) is called where self = Owner.attr, instance = None and owner = Owner.

When Owner is instantiated instance will be the instance of Owner.

Now I would like to apply this concept to method parameters instead of class attributes.

How it would look in practice (let's assume that the functionality of Attr is to wrap a string with a given string):

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'.

When accessing param, Attr.__get__(self, instance, owner) will be called with self = funct.param, instance = funct and owner = funct (although it doesn't make sense to have owner and instance the same, might be None?). But since funct is not a class, this will not work. How can I get something similar to work?

A decorator on the function will be processing the parameters, so this might add to the solution I think. The decorator must be, for example, be able to change the wrapper string.

役に立ちましたか?

解決

Functions actually are first class objects in Python, but you are correct in saying that the syntax you describe would not work as you want. You could potentially do something like this with a decorator that inspects the passed attributes for characteristics that would enable this sort of functionality though. However, you'd probably be better off implementing a callable object, then attaching descriptors to that and creating instances of the callable rather than functions.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top