Hello
What are Methods in Python Classes?
Definition
- When you write a function inside a class, it is called a method.
- There are 4 main types of methods in Python
Types:
| Type |
Instance Method |
Class Method |
Static Method |
Constructor |
| Keyword Used |
self |
cls |
None |
self |
| Special Symbol |
None |
@classmethod |
@staticmethod |
__init__() |
| Common Use |
Uses object data |
Uses class data |
Just a helper method, no self or cls |
Runs when object is created |
Hello
Hello
Hello
Instance Method
Definitions
- A method that works with object data
- Uses self → refers to the object
Syntax:
class Student:
def show(self): # instance method
print("This is an instance method")
s = Student()
s.show() # Output: This is an instance method
Hello
Hello
Hello
Class Method
Definitions
- Works with class-level data
- Uses cls → refers to the class, not the object
- Use @classmethod decorator
Syntax:
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print("School name is:", cls.school)
Student.show_school() # Output: School name is: ABC School
Hello
Hello
Static Method
Definitions
- Doesn’t use self or cls
- Just a normal function inside a class
- Use @staticmethod decorator
Syntax:
class Student:
@staticmethod
def greet():
print("Welcome to the class!")
Student.greet() # Output: Welcome to the class!
Hello
Hello
Constructor Method – __init__()
Definitions
- A special method that runs automatically when an object is created
- Used to give starting values to the object
Syntax:
class Student:
def __init__(self, name):
self.name = name
def show_name(self):
print("Name is:", self.name)
s = Student("Kiran")
s.show_name() # Output: Name is: Kiran
Hello
Hello