Qnode decorator on a class method doesn't work

Hi! I’ve been trying to create a qnode within a class but having a little trouble doing this.

Some pseudo code:

class Circuit(object):

Then when I create the qnode I try referencing the dev_qubit in the wrapper like so:

def quantumcirc()…

But this raises an error because self cannot be passed this way in the decorator. If I use the following later on:

quantumcirc=qml.Qnode(quantumcirc, dev_qubit)

This also doesn’t seem to run. I’m not sure how to work around this! This is probably more a python/wrapper issue not a PennyLane one, but just wanted to ask in case there is a quick/obvious solution I’m missing! Thank you!

Hi amira,

I’ll take a guess at the problem here (hard to be 100% certain since you’ve only provided snippets of the code). Are you trying to make quantumcirc a method of the class Circuit? In that case, self is not accessible (since it is always appearing explicitly as part of function signatures). An easy alternative is sketched below:

class Circuit2(object):
    def __init__(self):
        self.dev_qubit = qml.device('default.qubit', wires=1)
    def quantumcirc(self, x):
        def _quantumcirc(x):
            return qml.expval.PauliY(wires=0)
        return _quantumcirc(x)

c2 = Circuit2()

Hope that helps!


Thanks Nathan! It does indeed.