#
Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Python Variables in OOPS

Hello
Hello

Hello

Hello

Variables in OOP

Definition

In Object-Oriented Programming (OOP), variables are categorized based on how and where they are declared. The two main types of variables in Python OOP are:

Hello

Hello

Instance Variables

Definition

Instance variables are variables that are unique to each object. They are defined inside the constructor (__init__) or other instance methods using self.

Where to define?

Inside __init__() using self.varname.

Key Points:

Syntax:

class Student:
    def __init__(self, name, age):
        self.name = name        # instance variable
        self.age = age          # instance variable

# Creating objects
s1 = Student("Mayank", 14)
s2 = Student("Aarul", 9)

print(s1.name, s1.age)  # Mayank 14
print(s2.name, s2.age)  # Aarul 9

Hello

Hello

Class Variables

Definition

Class variables are variables that are shared across all objects. They are defined inside the class but outside any instance method, typically at the top of the class body.

Where to define?

Directly inside the class (not in any method).

Key Points:

Syntax:

class Student:
    school_name = "DPS"  # class variable

    def __init__(self, name):
        self.name = name

s1 = Student("Mayank")
s2 = Student("Aarul")

print(s1.school_name)  # DPS
print(s2.school_name)  # DPS

Student.school_name = "KV"
print(s1.school_name)  # KV
print(s2.school_name)  # KV

Hello

Hello

Difference Table: Instance vs Class Variable

Hello

Instance Variable

Class Variable

Hello

Hello

Modifying Class Variable from Instance

Careful

When you modify a class variable via self, it creates a new instance variable instead of modifying the original.

Syntax:

class Student:
    school = "DPS"  # class variable

    def __init__(self, name):
        self.name = name

s1 = Student("Mayank")
s1.school = "KV"  # creates instance variable, doesn't change class variable

print(s1.school)          # KV (instance-level)
print(Student.school)     # DPS (unchanged)

How

Accessing and Updating Class Variables Properly

Syntax:

class Student:
    school = "DAV"

    @classmethod
    def change_school(cls, new_name):
        cls.school = new_name

Student.change_school("KV")
print(Student.school)  # KV


What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #