An instance method is the default method type in a Python class. It takes
selfas its first parameter, giving it full access to all attributes and other methods belonging to that specific object instance.
class CoffeeCup:
def __init__(self, size):
self.size = size # Instance attribute
def drink(self): # Instance Method
return f"Drinking a delicious {self.size} coffee!"
# Usage
my_cup = CoffeeCup("Large")
print(my_cup.drink()) # Output: Drinking a delicious Large coffee!A class method is marked with the
@classmethoddecorator. It takesclsas its first parameter, pointing directly to the class structure itself. It can modify class-level state that applies to all instances.
class CoffeeCup:
def __init__(self, ounces):
self.ounces = ounces
@classmethod
def from_size_name(cls, size_name): # Class Method (Factory)
if size_name == "Large":
return cls(16) # Creates an instance: CoffeeCup(16)
return cls(8) # Default to Small
# Usage: Create an object without calling __init__ directly
large_cup = CoffeeCup.from_size_name("Large")
print(large_cup.ounces) # Output: 16A static method is marked with the
@staticmethoddecorator. It does not take aselfor aclsparameter. It behaves exactly like a regular, isolated function, but it is placed inside the class because it belongs there logically.When to use: For utility or helper functions that perform a calculation but don't need to read or change any class or instance data.
class CoffeeCup:
@staticmethod
def celsius_to_fahrenheit(celsius): # Static Method
return (celsius * 9/5) + 32
# Usage: Call directly on the class without creating an object
print(CoffeeCup.celsius_to_fahrenheit(90)) # Output: 194.0Feature | Instance Method | Class Method ( | Static Method ( |
|---|---|---|---|
First Parameter |
|
| None |
Access Level | Can access/modify instance & class data. | Can access/modify class data only. Cannot touch instance data. | Isolated. Cannot access instance or class data. |