Defining a Class in Python includes these components:
- Adding Instance Variables
- Adding Instance Methods
- Adding Class Variables
- Adding Class Methods
- Adding Static Methods
1.) Adding Instance Variables:
Instance variables are defined inside methods and unique to each object.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age2.) Adding Instance Methods:
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()3.) Adding Class Variables:
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 Corp4.) Adding Class Methods:
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: NewTech5.) Adding Static Methods:
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