Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Defining a Class in Python

Defining a Class in Python

Defining a Class in Python includes these components:

  • Adding Instance Variables
  • Adding Instance Methods
  • Adding Class Variables
  • Adding Class Methods
  • Adding Static Methods

Instance variables are defined inside methods and unique to each object.

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

Instance methods operate on instance variables.

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

    def display(self):
        print(f"Student Name: {self.name}")

s = Student("John")
s.display()

Class variables are shared among all instances.

class Employee:
    company = "Tech Corp"  # Class variable

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

e1 = Employee("Alice")
e2 = Employee("Bob")
print(e1.company, e2.company)  # Output: Tech Corp Tech Corp

Class methods operate on class variables.

class Employee:
    company = "Tech Corp"

    @classmethod
    def change_company(cls, new_name):
        cls.company = new_name

Employee.change_company("NewTech")
print(Employee.company)  # Output: NewTech

Static methods don’t operate on instance or class variables.

class MathOperations:
    @staticmethod
    def add(a, b):
        return a + b

print(MathOperations.add(5, 3))  # Output: 8

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *