python add an attribute to a method using decorators
<p>I'm trying to add an attribute to my method using decorators to determine if it has been called. I can't figure out why I got this error : TypeError: bet() missing 1 required positional argument: 'betsize'. </p>

<p>file game.py</p>

<pre><code>class Game(object):
    def __init__(self):
        ..

    @AddCalled
    def bet(self, betsize):
        print(betsize)
</code></pre>

<p>file addcalled.py :</p>

<pre><code>class AddCalled(object):
    def __init__(self, f):
        self.f = f
        self.called = False

    def __call__(self, *args, **kwargs):
        self.f(*args, **kwargs)
        self.called = True
</code></pre>

<p>I get the betsize from a Qt signal (button click). The target slot function is bet() from game.py</p>

<p>file mainui.py</p>

<pre><code>class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    ..

    self.connect(self.ui.btnBet, SIGNAL("clicked()"), self.bet)

    def bet(self):
        #assuming 'game' is an instance of Game()
        self.game.bet(self.ui.betLine.text())
</code></pre>

<p>Now I got this error whenever I click on the bet button </p>

<pre><code>Traceback (most recent call last):
  File "/home/njl/projet/mainui.py", line 27, in bet
    self.game.bet(self.ui.betLine.text())
  File "/home/njl/projet/addcalled.py", line 15, in __call__
    self.f(*args, **kwargs)
TypeError: bet() missing 1 required positional argument: 'betsize'
</code></pre>

<p>I would appreciate some help. Litteraly stuck in there.</p>

<p>Your decorator doesn't properly pass <code>self</code> to the wrapped function.</p>

<p>Normally, <code>self</code> is added by the descriptor mechanism of function objects, which converts them on the fly into method objects with the <code>self</code> rolled in.  But you replaced your method with an AddDecorator object, which doesn't implement the descriptor protocol, so when your AddDecorator wrapper is called, it doesn't know what instance it's being called on (i.e., what <code>self</code> should be).</p>

<p>You could implement the descriptor protocol on your AddDecorator class by giving it a <code>__get__</code> method.  Or you could just write a regular decorator using a function:</p>

<pre><code>def addCalled(func):
    def newFunc(*args, **kwargs):
        newFunc.called = True
        func(*args, **kwargs)
    newFunc.called = False
    return newFunc
</code></pre>

python qt class decorator