Home > Software engineering >  Class_name.apply syntax in python
Class_name.apply syntax in python

Time:11-16

I am new to object oriented programming and pytorch framework. I am stuck with the usage of syntax shown below:

self. variable_name=  some_class_name.apply

It would be great if someone can explain me this kind of syntax.

I tried searching this on various websites but could not find any appropriate solution. I saw the usage of this syntax when I was trying to understand the below code: https://github.com/liangqiyao990210/Quantum-Deep-Learning/blob/master/qiskit_demo/qiskit_demo.ipynb Thank you for great help.

CodePudding user response:

In python, assigning a function or method to a variable means that the assigned variable is a reference of the function or method. For example, we define a function func:

def func(x): 
    return x**2

and then we assign func to a variable g: g=func. After that, we can directly call the function func by calling g:

>>> g(3)
>>> 9
>>> func(3)
>>> 9

In other words, g is an alias of the function func.

In the link you've mentioned, self.qc = TorchCircuit.apply simply means that we create a reference of TorchCircuit.apply and assign it to self.qc. Calling self.qc(x) is totally equal to calling TorchCircuit.apply(x)

References:

https://www.geeksforgeeks.org/assign-function-to-a-variable-in-python/

Assigning a function to a variable

CodePudding user response:

I'm not familiarized with pytorch framework but maybe this can help you understand what the attribute self is for:

What is the use of Self in Python? Python - self in python - edureka The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. Join our Master Python programming course to know more. In Python, we have methods that make the instance to be passed automatically, but not received automatically.

Example:

class food():

init method or constructor

def init(self, fruit, color): self.fruit = fruit self.color = color

def show(self): print("fruit is", self.fruit) print("color is", self.color )

apple = food("apple", "red") grapes = food("grapes", "green")

apple.show() grapes.show()

source: https://www.edureka.co/blog/self-in-python/

  • Related