Types of Class Variables in Python


Types of Class Variables in Python

1. Instance Variable
Definition:

  • Instance variables are specific to each object.
  • They are defined using the self keyword inside the constructor (__init__ method).
  • Each object has its own separate copy of instance variables.

Program:

class Car:
    # Constructor with instance variables
    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price

    # Method to display car details
    def display_details(self):
        print("Brand:", self.brand)
        print("Model:", self.model)
        print("Price:", self.price)

# Creating objects of the Car class with different values
car1 = Car("Toyota", "Corolla", 20000)
car2 = Car("Honda", "Civic", 22000)
car3 = Car("Ford", "Mustang", 30000)

# Displaying details of each car
car1.display_details()
print()  # Line break for better readability
car2.display_details()
print()
car3.display_details()


Output:

Brand: Toyota
Model: Corolla
Price: 20000

Brand: Honda
Model: Civic
Price: 22000

Brand: Ford
Model: Mustang
Price: 30000


2. Class Variable:


Definition:

  • Class variables are shared among all objects of the class.
  • They are defined outside the constructor and are not prefixed with self.
  • Changing a class variable affects all objects of that class.

Program:

class Laptop:
    # Class variable
    os = "Windows 11"

    # Constructor with instance variables
    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price

    # Method to display laptop details
    def display_details(self):
        print("Brand:", self.brand)
        print("Model:", self.model)
        print("Price:", self.price)
        print("Operating System:", Laptop.os)

# Creating objects of the Laptop class
laptop1 = Laptop("Dell", "XPS 13", 1200)
laptop2 = Laptop("HP", "Spectre x360", 1400)
laptop3 = Laptop("Lenovo", "ThinkPad X1", 1500)

# Displaying details of each laptop
laptop1.display_details()
print()  # Line break for better readability
laptop2.display_details()
print()
laptop3.display_details()


Output:

Brand: Dell
Model: XPS 13
Price: 1200
Operating System: Windows 11

Brand: HP
Model: Spectre x360
Price: 1400
Operating System: Windows 11

Brand: Lenovo
Model: ThinkPad X1
Price: 1500
Operating System: Windows 11

Post a Comment

0 Comments