Defining class global variables in Python
A global variable is a variable that is visible and available in every part of the program.
Global variables are also not defined in any function or method. On the other hand, local variables are defined in functions and can be used only in those functions.
The global scope or environment consists of a set of variables that are visible throughout the program. In Python, a scope may be an area within a Python program where variables, functions, or modules can be accessed and used.
Typically, in programming, global scope replaces block scope and local scope.
In programming, a variable is referred to as a memory location that can be used to store values. However, in Python, variables created under a class are called class variables, while variables declared under a specific object may be called instance variables.
Class variables are usually declared under the class definition outside all methods and other variables whereas global class variables are declared outside the class. They can be accessed by any method and class.
The global variables are defined as follows.
model = "SPlaid"
class Cars:
As shown below, any class or method within a class can access a global variable by simply calling the variable name. Multiple classes and methods can also access a global variable at the same time.
car_type = "SUV"
print("Outside all classes", car_type)
class Tesla:
print("Type of the car within the Tesla class is:", car_type)
def __init__(self, car_type):
self.car_type = car_type
def display_tesla(self):
print("Type of car within a Tesla method:", car_type)
# creating object to access method
#
tsl_object = Tesla(car_type)
tsl_object.display_tesla()
class Lucid:
print("Type of the car within the Lucid class is:", car_type)
def __init__(self, car_type):
self.car_type = car_type
def display_lucid(self):
print("Type of the car within the Lucid method:", car_type)
# creating an object to access the method within the Lucid Class.
lucid_object = Lucid(car_type)
lucid_object.display_lucid()
Output:
Outside all classes SUV
Type of the car within the Tesla class is: SUV
Type of car within a Tesla method: SUV
Type of the car within the Lucid class is: SUV
Type of the car within the Lucid method: SUV
Defining class variables as global variables
We can also global
modify a local scope variable to make it available in the global scope using the keyword.
Any variable defined within a function is considered a local variable and hence can be used only within the local scope. However, using the global keyword, we can change the scope of a local variable to be globally accessible.
Similarly, we can also make class variables accessible outside the class defined using global keyword. Class variables can be used by other classes and methods outside of that particular class.
In the following code snippet, we will try to use a class variable outside the class. We will definitely get an error letting us know that the variable is not defined.
class Tesla:
# creating a class variable
speed = 60
print("Acessing speed variable within the class:", speed)
def __init__(self, speed):
self.speed = speed
def display_speed():
print("Speed of the Tesla is:", speed)
print("Accessing the class variable outside the Tesla Class", speed)
Output:
print("Accessing the class variable outside the Tesla Class", speed)
NameError: name 'speed' is not defined
As shown in the code example above, we are trying to access a class variable defined in the class Tesla. However, this will result in an error because variables declared in a class can only be accessed within that class alone.
However, as mentioned earlier, we can avoid this error by using the global keyword before defining the class variable. Only then we can access the variable outside the class.
class Tesla:
# creating a class variable and making it a variable
global speed
speed = 60
print("Accessing speed variable within the class:", speed)
def __init__(self, speed):
self.speed = speed
def display_speed():
print("Speed of the Tesla is:", speed)
print("Accessing the class variable outside of the Tesla class", speed)
Output:
Accessing speed variable within the class: 60
Accessing the class variable outside of the Tesla class 60
Once we declare a class variable as global, it can be accessed outside its own class and in other classes.
In the above code snippet, we access the speed variable defined as a global variable in the Tesla class from the Lucid class. Unlike the previous example where we got an error, we can access the variable because it is now available in the global scope.
class Tesla:
# creating a class variable and making it a global variable
global speed
speed = 60
print("Acessing speed variable within the class:", speed)
def __init__(self, speed):
self.speed = speed
def display_speed():
print("Speed of the Tesla is:", speed)
# accessing the speed variable from outside the class
print("Accessing the class variable", speed)
class Lucid:
# accessing the speed variables from a different class
print("Accessing the speed variable from a different class:", speed)
Output:
Accessing speed variable within the class: 60
Accessing the class variable 60
Accessing the speed variable from a different class: 60
Interestingly, a declared global variable, such as the speed variable, can also be accessed and used by a method of another class.
For example, in the following code diagram, the method defined in the Lucid class can access the speed variable. This is possible only when the global keyword precedes the class variable before the declaration.
class Tesla:
# creating a class variable and making it a global variable
global speed
speed = 60
print("Accessing speed variable within the class:", speed)
def __init__(self, speed):
self.speed = speed
def display_speed():
print("Speed of the Tesla is:", speed)
print("Accessing the class variable", speed)
class Lucid:
print("Accessing the speed variable from a different class:", speed)
def __init__(self, speed):
self.speed = speed
def display_tesla_speed(self):
print("Accessing the speed variable from a method in another class:", speed)
lucid_object = Lucid(speed)
lucid_object.display_tesla_speed()
Output:
Accessing speed variable within the class: 60
Accessing the class variable 60
Accessing the speed variable from a different class: 60
Accessing the speed variable from a method in another class: 60
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Implementing a Low-Pass Filter in Python
Publish Date:2025/05/07 Views:89 Category:Python
-
Low pass filter is a term in signal processing basics and is often used to filter signals to obtain more accurate results. This tutorial will discuss the low-pass filter and how to create and implement it in Python. A low-pass filter is use
Implementing Curl command in Python using requests module
Publish Date:2025/05/07 Views:97 Category:Python
-
requests This article will discuss and implement different curl commands using the module in Python . requests Installing modules in Python Python provides us with requests the module to execute curl command. Install it in Python 3 using Pi
Using fetchall() in Python to extract elements from a database
Publish Date:2025/05/07 Views:171 Category:Python
-
This article aims to describe fetchall() the working methods of extracting elements from a database using and how to display them correctly. This article will also discuss list(cursor) how functions can be used in programs. fetchall() Extra
Parsing log files in Python
Publish Date:2025/05/07 Views:106 Category:Python
-
Log files contain information about events that occurred during the operation of a software system or application. These events include errors, requests made by users, bugs, etc. Developers can further scan these usage details to find poten
Declaring a variable without a value in Python
Publish Date:2025/05/07 Views:57 Category:Python
-
A variable is a reserved memory location that can store some value. In other words, variables in a Python program provide data to the computer to process operations. Every value in Python has a data type. There are numbers, lists, tuples, e
Pretty Printing Dictionaries in Python
Publish Date:2025/05/07 Views:126 Category:Python
-
This tutorial will show you how to pretty print dictionaries in Python. Pretty printing means presenting some printed content in a more readable format or style. pprint() Pretty printing dictionaries in Python pprint is a Python module that
Writing logs to a file in Python
Publish Date:2025/05/06 Views:133 Category:Python
-
This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file
Comparing two dates in Python
Publish Date:2025/05/06 Views:97 Category:Python
-
This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin
Reload or unimport modules in Python
Publish Date:2025/05/06 Views:59 Category:Python
-
Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu