user1 and user2:
class User:
# Class Variables
max_login_attempts = 5
password_min_length = 8
system_name = "hasabTech Portal"
def __init__(self, username):
# Instance Variable
self.username = username
# Creating two different user instances from this class:
user1 = User("Shameel")
user2 = User("Ammad")
# Print the value of all class variables using user1 instance:
print(f"User 1 Max Login Attempts: {user1.max_login_attempts}")
print(f"User 1 Min Pass Length: {user1.password_min_length}")
print(f"User 1 System Name: {user1.system_name}")
# Print the value of all class variables using user2 instance:
print(f"User 2 Max Login Attempts: {user2.max_login_attempts}")
print(f"User 2 Min Pass Length: {user2.password_min_length}")
print(f"User 2 System Name: {user2.system_name}")
In the case of an instance variable, you are bound to access it using the instance name. However, in case of accessing class variables, it's a matter of choice how one wants to access a class variable. As a general rule of thumb, it is preferred to use pattern # 1 i.e., access class variable using Class name.
Summary
What are Class Variables?
Class variables (also known as class attributes) are shared across all instances (objects) of a class. They belong to the class itself, not to any specific instance.
Two ways of accessing the values of a Class Variable
- Access by Class name:
Class.classVariableName
- Access by Instance name:
Instance.classVariableName
Stay connected with hasabTech for more information:
Website | Facebook | LinkedIn | YouTube | X (Twitter) | TikTok