Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
global variables
#1
I've read a view posts and articles about global variables so I don't understand why it doesn't work in my app.
In the code below pos1, pos2 and pos2 create an error at keyPressEvent: "local variable 'pos...' referenced before assignment".
Why? And how can I do it right?
pos is an index that I want to increase/decrease at keypress.

import sys global pos1 class MainWindow(QtWidgets.QMainWindow): global pos2 pos2 = 1 pos1 = 1 def __init__(self): super().__init__() global pos3 pos3 = 1 # main window self.setWindowTitle("Uhren II") self.setFixedSize(500, 500) self.setWindowIcon(QIcon("Uhren2.ico")) # ... def keyPressEvent(self, event): if type(event) == QtGui.QKeyEvent and (event.key() == QtCore.Qt.Key_Left or event.key() == QtCore.Qt.Key_Down) : pos1 -= 1 pos2 -= 1 pos3 -= 1 if type(event) == QtGui.QKeyEvent and (event.key() == QtCore.Qt.Key_Right or event.key() == QtCore.Qt.Key_Up) : pos1 += 1 pos2 += 1 pos3 += 1 print(pos1, pos2, pos3) app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() app.exec()
Reply
#2
The error means that you are trying to use a variable that is not set. Globals are usually frowned upon. If you want a variable used throughout the class use self.variable in the class.

class MyClass: def __init__(self, variable): self.variable = variable # This variable can be used throughout the class def show(self): return f'{self.variable} in the show function' def mydef(self): return f'{self.variable} in the mydef function' def __str__(self): return f'{self.variable} in the __str__ function'
Output:
my variable in the __str__ function my variable in the show function my variable in the mydef function
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#3
The "global" word tells Python to look for a variable in the global scope, not the local scope.

This is meaningless, because this variable is already in the global scope.
import sys global pos1
This is very odd.
class MainWindow(QtWidgets.QMainWindow): global pos2
Normally you would declare pos2 to be a class variable. A class variable is like a global variable, but it is only global to instances of the class. Your code does not result in a class that has pos2 as an attribute. This is better shown in the example below:
global_variable = 1 class A: global global_variable global_variable = 2 class_variable = 3 print(global_variable, A.class_variable) print(A.global_variable)
Output:
2 3 Traceback (most recent call last): File "...", line 11, in <module> print(A.global_variable) AttributeError: type object 'A' has no attribute 'global_variable'. Did you mean: 'class_variable'?
As you can see, the global keyword told Python to not create a variable named "global_variable". When global_variable = 2 is assigned in the class, it sets the value of the global variable. Since the assignment is to a global variable, the assignment inside the class does not create a class variable. We can access A.class_variable, but we cannot access A.global_variable because it was never created.

This is even odder
 def __init__(self): super().__init__() global pos3 pos3 = 1
Now you have code that assigns a global variable when instances of that class are created. The global variable does not exist until this happens, No instance variable is created. I cannot think of a reason for using "global" inside a class or a method. Python allows it, but it doesn't make any sense.

Since all you have are global variables, this needs to use the global keyworkd:
 def keyPressEvent(self, event): global pos1, pos2, pos3 if type(event) == QtGui.QKeyEvent and (event.key() == QtCore.Qt.Key_Left or event.key() == QtCore.Qt.Key_Down) :
This code will no longer crash. It is code that doesn't make any sense at all, but it will not crash.

Use class and instance variables instead of global variables. This example creates one of each. class_variable is a class variable and it is shared by all instances of the class, instance_variable is an instance variable and it is unique for each instance of the class.
class MainWindow: class_variable = 0 def __init__(self): super().__init__() self.instance_variable = 0 def keyPressEvent(self): self.__class__.class_variable += 1 self.instance_variable += 1 a = MainWindow() b = MainWindow() a.keyPressEvent() b.keyPressEvent() print(a.class_variable, a.instance_variable, b.instance_variable)
Output:
2 1 1
Each time the keyPressEvent method gets called it increments the class and instance variable. Each instance was clicked once, so each instance_variable was incremented once, but since there were two clicks, the class_variable was incremented twice.
Reply
#4
Thanks for all that solutions.
In the meantime I also solfed the problem with a new class.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand global variables 357mag 5 3,067 May-12-2023, 04:16 PM
Last Post: deanhystad
  Global variables or local accessible caslor 4 2,999 Jan-27-2023, 05:32 PM
Last Post: caslor
  Clarity on global variables JonWayn 2 2,442 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 11,028 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 4,383 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 7,119 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Question regarding local and global variables donmerch 12 8,799 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 5,899 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 6,054 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  Please help me understand how to use global variables joew 6 5,695 Jan-05-2020, 06:03 PM
Last Post: joew

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.