← Назад к вопросам
Как создать оператор в Python?
1.8 Middle🔥 151 комментариев
#Python Core#Архитектура и паттерны
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Как создать оператор в Python
Язык Python не позволяет создавать новые операторы синтаксиса. Однако можно перегружать существующие операторы через специальные методы (magic methods / dunder methods). Это даёт иллюзию создания новых операторов для пользовательских типов.
1. Принцип: операторы — это методы
Все операторы в Python вызывают методы:
a + b вызывает a.__add__(b)
a - b вызывает a.__sub__(b)
a == b вызывает a.__eq__(b)
a[i] вызывает a.__getitem__(i)
Пример:
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Number(self.value + other.value)
def __repr__(self):
return f"Number({self.value})"
a = Number(5)
b = Number(3)
result = a + b # Вызывает a.__add__(b)
print(result) # Number(8)
2. Арифметические операторы
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __truediv__(self, scalar):
return Vector(self.x / scalar, self.y / scalar)
def __pow__(self, power):
return Vector(self.x ** power, self.y ** power)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(v1 * 2) # Vector(2, 4)
3. Операторы сравнения
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
def __le__(self, other):
return self.age <= other.age
def __gt__(self, other):
return self.age > other.age
def __ge__(self, other):
return self.age >= other.age
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1 > p2) # True
print(sorted([p1, p2]))
4. Операторы присваивания (in-place)
class Counter:
def __init__(self, value):
self.value = value
def __iadd__(self, other):
self.value += other
return self
def __isub__(self, other):
self.value -= other
return self
def __repr__(self):
return f"Counter({self.value})"
c = Counter(10)
c += 5 # Вызывает __iadd__
print(c) # Counter(15)
5. Индексирование и срезы
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
def __setitem__(self, index, value):
self.items[index] = value
def __delitem__(self, index):
del self.items[index]
def __len__(self):
return len(self.items)
def __contains__(self, item):
return item in self.items
ml = MyList([1, 2, 3, 4, 5])
print(ml[0]) # 1
ml[1] = 20
print(ml[1]) # 20
print(3 in ml) # True
print(len(ml)) # 5
6. Вызов объекта (оператор ())
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
mul_by_3 = Multiplier(3)
print(mul_by_3(5)) # 15
values = [1, 2, 3, 4, 5]
result = list(map(mul_by_3, values))
print(result) # [3, 6, 9, 12, 15]
7. Битовые операторы
class BitSet:
def __init__(self, value=0):
self.value = value
def __and__(self, other):
return BitSet(self.value & other.value)
def __or__(self, other):
return BitSet(self.value | other.value)
def __xor__(self, other):
return BitSet(self.value ^ other.value)
def __lshift__(self, n):
return BitSet(self.value << n)
def __rshift__(self, n):
return BitSet(self.value >> n)
def __repr__(self):
return f"BitSet({self.value})"
a = BitSet(5) # 0101
b = BitSet(3) # 0011
print(a & b) # BitSet(1)
print(a | b) # BitSet(7)
print(a << 2) # BitSet(20)
8. Преобразование типов
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __int__(self):
return int(self.celsius)
def __float__(self):
return float(self.celsius)
def __str__(self):
return f"{self.celsius}C"
def __repr__(self):
return f"Temperature({self.celsius})"
def __bool__(self):
return self.celsius != 0
t = Temperature(25.5)
print(int(t)) # 25
print(float(t)) # 25.5
print(str(t)) # 25.5C
print(bool(t)) # True
9. Контекстные менеджеры
class Resource:
def __enter__(self):
print("Acquiring resource")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Releasing resource")
return False
with Resource() as r:
print("Using resource")
# Output:
# Acquiring resource
# Using resource
# Releasing resource
10. Практический пример: выражения
class Expr:
def __add__(self, other):
return AddOp(self, other)
def __sub__(self, other):
return SubOp(self, other)
def __mul__(self, other):
return MulOp(self, other)
class Num(Expr):
def __init__(self, value):
self.value = value
def eval(self):
return self.value
def __repr__(self):
return str(self.value)
class BinOp(Expr):
def __init__(self, left, right):
self.left = left
self.right = right
class AddOp(BinOp):
def eval(self):
return self.left.eval() + self.right.eval()
def __repr__(self):
return f"({self.left} + {self.right})"
class MulOp(BinOp):
def eval(self):
return self.left.eval() * self.right.eval()
def __repr__(self):
return f"({self.left} * {self.right})"
x = Num(5)
y = Num(3)
expr = x * y + x
print(expr) # ((5 * 3) + 5)
print(expr.eval()) # 20
Таблица операторов
Арифметика: add, sub, mul, truediv, floordiv, mod, pow Сравнение: eq, ne, lt, le, gt, ge Битовые: and, or, xor, lshift, rshift, invert Другое: getitem, setitem, len, call, enter, exit
Заключение
В Python нельзя создавать новые операторы, но можно перегружать существующие. Это позволяет создавать интуитивный API для пользовательских типов, где математические операции применяются естественно.