Class or Static Variable in Python
- Get link
- X
- Other Apps
Class or Static Variable in Python
In Python, a class variable (also called a static variable) is a variable that is shared by all instances of a class. It is defined inside the class definition, but outside of any method definition. A class variable can be accessed using the class name or an instance of the class.
Here's an example of a class with a class variable:
class Car: # Class variable num_cars = 0 def __init__(self, make, model, year): self.make = make self.model = model self.year = year Car.num_cars += 1 # Create some Car objects c1 = Car('Honda', 'Civic', 2020) c2 = Car('Toyota', 'Corolla', 2019) # Print the number of cars created print(Car.num_cars) # Output: 2
In the example above, we define a Car
class with a class variable num_cars
. The __init__()
method initializes the object's attributes make
, model
, and year
, and increments the num_cars
class variable. We create two Car
objects c1
and c2
, and then print the num_cars
class variable using the class name Car
.
The output of the program shows that two Car
objects were created, so the value of num_cars
is 2.
Class variables can be useful for storing information that is common to all instances of a class, such as a counter of the number of objects created, or a default value that should be shared among all instances. Note that if you modify the value of a class variable using an instance of the class, it will affect all other instances of the class as well, since the variable is shared among all instances.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments