Python Class Functions and self using

Viewed 57

I need to learn about the using variables on function in same class.

For example my class is like in below:

class MainWindow(QMainWindow):
    def __init__(self,parent = None):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
    def myFunc1(self):
        self.myVariable = 5 

    def myFunc2(self):
        print(self.myVariable) #gives me 5

When I defined to variable like self.myVariable in myFunc1 I get its value from myFunc2. So If I use the self.does that make it a global variable ?

If I use like local variable in function, should i use it without self ?

2 Answers

If use use self to define a variable that makes it an object variable (attribute). Every object of the class will has that variable (for different objects it can contains different values). To define local variable (only for function in class) you don't need to use self.

You can read more about self in python here.

Attributes that you assign to self under class methods are carried along with the self / object. So that when you create an attribute (such as in your example : self.myVariable=5 in one of the class method), you can reach to this attribute from other class methods, too.

And yes, if you want a local variable that borns and dies in a method, you don't need to attach it to self.

Related