Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I access an decorated class's instance from inside a class decorator?

Here's an example of what I mean:

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()

Do I need to decorate the actual class?

like image 750
orokusaki Avatar asked Feb 02 '10 01:02

orokusaki


People also ask

How do you use a decorator inside class?

Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that's why we use “@A. Decorators” here.

How do you call a class decorator in Python?

To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function. Here, when we decorate, multiply_together with integer_check, the integer function gets called.

How do I read a Python decorator?

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

What does __ call __ do in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.


2 Answers

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
like image 103
jldupont Avatar answered Oct 03 '22 18:10

jldupont


Please notice in this context that the use of "self" is just a convention, a method just uses the first argument as a reference to the instance object:

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

e = Example('hello')
e.method('world')
like image 30
snies Avatar answered Oct 03 '22 17:10

snies