Using decorators inside a class
<p>I am trying to implement a simple logging feature within my app.</p>

<pre><code>class messages(object):

    # Implement decorator here
    def on(self):
        def wrapper():
            # Do something here
        return wrapper

    def off(self):
        def wrapper():
            # Do something here
        return wrapper


class website(object):

    @messages.on #This line can be switched on/off
    def login(self):
        # Do a whole bunch of stuff here
        self.response = "[+] Login Succeeded!"

website = website()
website.login() # prints self.response based on @messages.on/off
</code></pre>

<p>But i am not sure what i need to apply in my decorator. I have tried creating instances and adding params but mostly receive TypeError. I am fairly new to decorators. Any help would be appreciated and i'd love to remember this for next time.</p>

<p>Below is the sample decorator that you may use:</p>

<pre><code>class Utilities:

    @staticmethod
    def add_logger(func):
        def wrapped_func(*args, **kwargs):
            # Sample logic, feel free to update this
            try:
                func_response = func(*args, **kwargs)
            except:
                print 'I am error handled by logger'
                func_response = None
            return func_response
        return wrapped_func
</code></pre>

<p>Let's define your class now:</p>

<pre><code>class Dog(object):

    @Utilities.add_logger 
    def bark(self):
        print 'In bark'

    @Utilities.add_logger 
    def my_error_function(self):
        print 'In my_error_function'
        raise Exception  # &lt;--- Raises Exception
</code></pre>

<p>Now, let's check how it works:</p>

<pre><code>&gt;&gt;&gt; dog = Dog()
&gt;&gt;&gt; dog.bark()
In bark
&gt;&gt;&gt; dog.my_error_function()
In my_error_function
I am error handled by logger  # Content from logger in case of exception
</code></pre>

<p><strong><em>Note:</strong> You shouldn't really be creating a <code>class</code> here to store utility function. Create a separate utility file and write such functions over there.</em></p>

<p>Without class, your decorator should be like (let's say in <em>utility.py</em>):</p>

<pre><code>def add_logger(func):
    def wrapped_func(*args, **kwargs):
        # Sample logic, feel free to update this
        try:
            func_response = func(*args, **kwargs)
        except:
            print 'I am error handled by logger'
            func_response = None
        return func_response
    return wrapped_func
</code></pre>

<p>For using it, simply do:</p>

<pre><code>import utility

class Dog(object):

    @utility.add_logger
    def bark(self):
        print 'In bark'
</code></pre>

python oop decorator