Python: Как я получаю доступ к экземпляру украшенного класса из декоратора класса?

Вот пример того, что я имею в виду:

class MyDecorator(object):    
    def __call__(self, func):
        # At which point would I be able to access the decorated method's parent class's instance?
        # In the below example, I would want to access from here: myinstance
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper

class SomeClass(object):
    ##self.name = 'John' #error here
    name="John"

    @MyDecorator()
    def nameprinter(self):
        print(self.name)

myinstance = SomeClass()
myinstance.nameprinter()

Я должен украсить фактический класс?

6
задан efotinis 19 November 2010 в 21:35
поделиться

3 ответа

class MyDecorator(object):
    def __call__(self, func):
      def wrapper(that, *args, **kwargs):
        ## you can access the "self" of func here through the "that" parameter
        ## and hence do whatever you want        
        return func(that, *args, **kwargs)
      return wrapper
8
ответ дан 9 December 2019 в 22:34
поделиться

Обратите внимание в этом контексте, что использование «self» является просто соглашением, метод просто использует первый аргумент как ссылку на объект-экземпляр:

class Example:
  def __init__(foo, a):
    foo.a = a
  def method(bar, b):
    print bar.a, b

e = Example('hello')
e.method('world')
2
ответ дан 9 December 2019 в 22:34
поделиться

Я думаю, что lambdaj имеет особенности для такого рода вещей.

-121--4817694-

В JDK - нет. Есть в apache commons-lang :

ClassUtils.toClass (Object [] objects)

Но писать его самому совсем не больно.

-121--4817693-

Аргумент self передается в качестве первого аргумента. Кроме того, MyDecorator является классом, эмулирующим функцию. Проще сделать его фактической функцией.

def MyDecorator(method):
    def wrapper(self, *args, **kwargs):
        print 'Self is', self
        return method(self, *args, **kwargs)
    return wrapper

class SomeClass(object):
    @MyDecorator
    def f(self):
       return 42

print SomeClass().f()
1
ответ дан 9 December 2019 в 22:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: