B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Instance vs Class Variables | LiveCodeProgramming

Instance vs Class Variables in Python

In Python, instance variables are specific to each object, while class variables are shared by all objects of the class.

Python में instance variable हर object के लिए अलग होता है, जबकि class variable सभी objects में common होता है।

Example 1: Instance Variables
class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

e1 = Employee("Aryan", 25)
e2 = Employee("Naincy", 28)
print(e1.name, e1.age)
print(e2.name, e2.age)

Output:

Aryan 25
Naincy 28

Each object has its own values. These are instance variables.

हर object के पास अपने खुद के values होते हैं। ये instance variables हैं।

Example 2: Class Variable Shared
class Employee:
    company = "LiveCodeProgramming"
    def __init__(self, name):
        self.name = name

e1 = Employee("Abhi")
e2 = Employee("Meena")
print(e1.company)
print(e2.company)

Output:

LiveCodeProgramming
LiveCodeProgramming

Class variable is shared across all objects.

Class variable सभी objects में common होता है।

Example 3: Change Instance Variable
e1.age = 30
print(e1.age)

Output:

30

Changing instance variable only affects that object.

Instance variable को बदलने पर सिर्फ वही object affect होता है।

Example 4: Change Class Variable via Class
Employee.company = "NewTech"
print(e1.company)
print(e2.company)

Output:

NewTech
NewTech

Updating class variable affects all instances.

Class variable update करने पर सभी instances पर effect होता है।

Example 5: Override Class Variable with Instance Variable
e1.company = "CustomCompany"
print(e1.company)
print(e2.company)

Output:

CustomCompany
NewTech

If you override a class variable with instance variable, it creates a separate copy for that object.

Instance से override करने पर एक अलग copy बन जाती है।