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>

<ol>
<li><p>If you just want Dog to bark (like in the example), there is no need for enabling a decorator</p>

<pre><code>class Dog(object):
    def __init__(self):
        self.sound = "Woof!"

    def bark(self):
        return self.sound
</code></pre></li>
<li><p>If you want to enable logging for some functions in class, here is a code that does that with explanation in comments</p>

<pre><code>from functools import wraps

class Utilities(object):

    @staticmethod  # no default first argument in logger function
    def logger(f):  # accepts a function
        @wraps(f)  # good practice https://docs.python.org/2/library/functools.html#functools.wraps
        def wrapper(self, *args, **kwargs):  # explicit self, which means this decorator better be used inside classes only
            print("Before:", self.sound)
            result = f(self, *args, **kwargs)
            print("After:", self.sound)
            return result
        return wrapper


class Dog(object):
    def __init__(self):
        self.sound = "Woof!"

    @Utilities.logger
    def run(self):
        """Perform running movement"""
        print("Running")
</code></pre></li>
</ol>

<p>Example:</p>

<pre><code>&gt;&gt;&gt; dog = Dog()
&gt;&gt;&gt; dog.run()
Before: Woof!
Running
After: Woof!
</code></pre>

<p>Though after all there is no need to store decorators functionality in the <code>Utilities</code> class - it is better to have a separate module (file) named <code>utils</code> and put decorator there as a standalone function</p>

python oop decorator