Guidelines

Class Variables Shared Across Objects

A class variable is a variable that belongs to the class and whose value is shared across all objects created by that class.

Class variables are defined within the class declaration, usually at the top of the class definition.

Unlike instance variables which have independent values for each object created using the __init__ constructor, class variables have a shared value across all objects created by the class.


Example of Using Class Variables

Example of Using Class Variables
class MyClass: # Class variable class_variable = "Shared Variable" def __init__(self, name): # Instance variable self.name = name # Accessing class variable print(MyClass.class_variable) # Output: Shared Variable # Creating instances obj1 = MyClass("Object1") obj2 = MyClass("Object2") # Class variable shared by all instances print(obj1.class_variable) # Output: Shared Variable print(obj2.class_variable) # Output: Shared Variable # Modifying the class variable MyClass.class_variable = "Modified Value" print(obj1.class_variable) # Output: Modified Value print(obj2.class_variable) # Output: Modified Value # Instance variables remain individual print(obj1.name) # Output: Object1 print(obj2.name) # Output: Object2

In this code, class_variable is a class variable of the MyClass class, and its value is shared across all objects created by MyClass.

The instances obj1 and obj2 have their own name instance variables, which maintain independent values for each object.

Class variables can be accessed using the class name, and modifying the value of a class variable affects all instances.

Mission
0 / 1

Which statement about class variables is correct?

Class variables are stored separately for each object.

Class variables operate in the same way as instance variables.

Class variables are shared among all instances of a class.

Class variables can only be accessed if an instance is created.

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result