Methods
Instance, class, and static methods
Interview Relevant: Method types
Methods
Different types of methods in Python.
Code Examples
Instance, class, and static methods.
python
1class MyClass:
2 class_var = 0
3
4 # Instance method - accesses self
5 def instance_method(self):
6 return f"Instance: {self}"
7
8 # Class method - accesses cls
9 @classmethod
10 def class_method(cls):
11 return f"Class: {cls.class_var}"
12
13 # Static method - no access to class/instance
14 @staticmethod
15 def static_method():
16 return "Static method"
17
18obj = MyClass()
19obj.instance_method() # Needs instance
20MyClass.class_method() # Can use class
21MyClass.static_method() # No reference needed
22
23# Factory class method
24class Date:
25 def __init__(self, year, month, day):
26 self.year, self.month, self.day = year, month, day
27
28 @classmethod
29 def from_string(cls, date_string):
30 year, month, day = map(int, date_string.split('-'))
31 return cls(year, month, day)
32
33Date.from_string("2024-01-15")