Qnode decorator on a class method doesn't work


#1

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):
def__init__(self):
self.dev_qubit=qml.device(‘default.qubit’,wires=total)

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

@qml.qnode(self.dev_qubit)
def quantumcirc()…

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

dev_qubit=qml.device(‘default.qubit’,wires=total)
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!


#2

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):
        @qml.qnode(self.dev_qubit)   
        def _quantumcirc(x):
            qml.RX(x,wires=0)
            return qml.expval.PauliY(wires=0)
        return _quantumcirc(x)

c2 = Circuit2()
print(c2.quantumcirc(0.5))

Hope that helps!


#3

Thanks Nathan! It does indeed.