1. Class Definition & The Explicit `self` Receiver
Why Python Requires `self` in Method Signatures
- In Python, `self` represents the instance calling the method. Unlike C++ or Java where `this` is an implicit keyword, Python makes the instance receiver explicit.
- When you call `obj.method(arg)`, Python translates this under the hood into `ClassName.method(obj, arg)`.
- The `__init__` method is the object initializer (constructor), called immediately after the object is allocated by `__new__`.
class Student:
def __init__(self, name: str, gpa: float):
self.name = name # Instance attribute
self.gpa = gpa
def is_honors(self) -> bool:
return self.gpa >= 3.8
s = Student("Ada Lovelace", 3.95)
print(f"{s.name} honors: {s.is_honors()}")
💡 Key Takeaway: The first parameter of any instance method must be the instance receiver, conventionally named self.