2

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 ?

3
  • 1
    "If I use like local variable in function, should i use it without self ?": yes. Commented Dec 10, 2021 at 11:15
  • 1
    self is not a global variable, but tied to the class (instance). In fact, self refers directly to the class instance. Any variable set with self.myVariable and the like, are therefore tied to the class instance. They are not local to the class method, nor global (to the script or module), but tied to the class instance. Commented Dec 10, 2021 at 11:16
  • 1
    Using "self." is similar to using global variables, but they are not global. You can use that variable anywhere inside of your class. But of course they aren't really global variables. Commented Dec 10, 2021 at 11:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.