`self`
self is the conventional name of the first parameter of an instance method: the instance the method was called on. Python passes it automatically when you write order.total().
Detailed Explanation
A method is a function defined in a class body. When you look it up on an instance, Python binds the instance to the function and gives you a bound method. order.total is Order.total with order already filled in as the first argument. order.total() is then a call with no extra explicit arguments, even though def total(self) has one parameter.
The name self is a convention, not a keyword. def total(this): works. Do not do that. Every reader, linter, and tutorial expects self for instances and cls for class methods.
You must declare the parameter. def total(): inside a class is a function that takes no arguments. order.total() then raises TypeError: total() takes 0 positional arguments but 1 was given because the binding still tries to pass the instance. The error message is telling you the missing self.
Inside the method, self is how you reach instance state: self.sku, self.qty. Assigning self.sku = sku creates or updates an instance attribute. Assigning sku = sku creates a local that vanishes. Reading a name without self uses LEGB, which does not include the instance or the class.
Calling the method on the class requires you to pass the instance yourself: Order.total(order). That is what super().total() is doing under the hood, with a slightly different binding. Static methods do not receive self. Class methods receive the class as cls instead.
Storing a bound method (callback = order.total) keeps a reference to order. That is useful for hooks and is a reference-cycle risk if order also stores callback.
Code Examples
class Order:
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty
def label(self) -> str:
return f"{self.qty}×{self.sku}"
line = Order("A-1", 2)
print(line.label()) # 2×A-1
print(Order.label(line)) # 2×A-1, instance passed by hand
print(line.label.__self__ is line) # Trueclass Broken:
def label(): # missing self
return "x"
# Broken().label() # TypeError: takes 0 positional arguments but 1 was given# A bound method keeps the instance alive.
line = Order("A-1", 2)
hook = line.label
print(hook()) # 2×A-1Common Gotchas
Omitting `self` in the signature
the call still passes the instance, and you get a confusing `TypeError` about argument count.
`self` is not in LEGB as a special lookup
`sku` inside a method is not `self.sku`. Write `self.sku` or you will read a global or raise `NameError`.
Bound methods retain the instance
registering `self.handler` on a long-lived emitter can pin `self` in memory.
The name is convention
`cls` for `@classmethod`, `self` for instance methods. Tools depend on those names.