Python requires self as the explicit first parameter in instance method definitions because Python translates method calls like obj.method(arg) into plain function calls on the class—ClassName.method(obj, arg)—via the descriptor protocol, ensuring explicit visibility of instance state (self.attr) over local variables without hidden scoping rules.
Basic Example
class BankAccount:
def __init__(self, owner: str, balance: float = 0.0) -> None:
self.owner = owner # Binds attribute to the specific instance
self.balance = balance
def deposit(self, amount: float) -> float:
self.balance += amount
return self.balance
account = BankAccount("Amina", 100.0)
# 1. Recommended: Standard bound method call (Python passes `account` as `self` automatically)
print(account.deposit(50.0))
# Output: 150.0
# 2. Equivalent unbound function call on the class (reveals what Python does under the hood):
print(BankAccount.deposit(account, 25.0))
# Output: 175.0
Key Details & Edge Cases
- How Python binds
selfautomatically (the Descriptor Protocol):- Functions defined inside a
classbody are ordinary function objects stored inClassName.__dict__. Because Python functions implement__get__, accessingaccount.depositinvokesFunctionType.__get__(account, BankAccount), returning a lightweight bound method wrapper that prependsaccountas the first positional argument (self) when called.
- Functions defined inside a
- Explicit
selfeliminates ambiguity between local variables and instance attributes:- Unlike C++ or Java—where an unqualified
balance = 10inside a method can implicitly mutate a member field—Python has no variable declaration keywords (var/let). Requiringself.balancemakes it unmistakably clear whether you are creating a temporary local variable (balance = 10) or mutating instance state (self.balance = 10).
- Unlike C++ or Java—where an unqualified
- Why calling a method without
selfin the definition raisesTypeError:- Defining
def deposit(amount):and callingaccount.deposit(50)passes two arguments (accountand50) to a function expecting one, raisingTypeError: BankAccount.deposit() takes 1 positional argument but 2 were given.
- Defining
- When
selfis NOT used (vs.):: Receives the class itself (cls) as its first argument instead of an instance—used for alternative constructors (BankAccount.from_dict(data)).: Receives neitherselfnorcls—behaves like a plain function namespaced inside the class.
selfis a strong PEP 8 convention, not a reserved keyword:- Python syntactically allows any valid identifier name (e.g.,
this), though PEP 8 strictly mandatesselffor instance methods andclsfor class methods so linters, IDEs, and other Python developers immediately recognize method signatures.
- Python syntactically allows any valid identifier name (e.g.,
Comparison of Method Types in a Python Class
| Decorator / Method Type | Implicit First Argument Passed by Python | Can Access/Modify Instance Attributes (self.x)? |
Can Access/Modify Class Attributes (cls.x)? |
Best Used When |
|---|---|---|---|---|
| Regular Instance Method (no decorator) | self (the instance) |
Yes | Yes (via self.__class__ or ClassName) |
Reading or mutating state belonging to a specific object instance. |
|
cls (the class object) |
No (no instance exists yet) | Yes | Alternative constructors (e.g., from_json()) or factory methods that respect subclassing. |
|
None | No | No (unless hardcoded by class name) | Utility functions logically grouped with the class that depend on neither instance nor class state. |
You must log in or register to comment.
