all Python 3OOPterm
self
self
A reference to the current instance of the class. The first parameter of instance methods (the name is a convention).
Syntax
def method(self): self.x = ...
self isn't a keyword but an ordinary first parameter: Python fills it with the instance automatically when you write b.double(), so you never pass it yourself. Forgetting the self. prefix is a common bug — size = 2 makes a local variable that vanishes when the method ends, while self.size = 2 actually changes the object.
Examples
class Box:
def __init__(self, size):
self.size = size
def double(self):
self.size *= 2
b = Box(5)
b.double() # то же, что Box.double(b): self — это b
print(b.size) # → 10
class Node:
def __init__(self, val):
self.val = val
self.next = None
def set_next(self, node):
self.next = node
n1 = Node(1)
n2 = Node(2)
n1.set_next(n2)
print(n1.next.val) # → 2
class Builder:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
return self # цепочка!
def build(self):
return self.items
b2 = Builder().add(1).add(2).add(3).build()
print(b2) # → [1, 2, 3]
# Передача self явно
class Calc:
def sq(self):
return self.n ** 2
c2 = Calc()
c2.n = 5
print(Calc.sq(c2)) # → 25 (явно)
class Logger:
prefix = '[LOG]'
def log(self, msg):
print(f'{self.prefix} {msg}')
l = Logger()
l.prefix = '[INFO]'
l.log('test') # → [INFO] test
See also
Open in the full glossarydocs.python.orgReport an inaccuracy