__neg__ — Easy Examples
Defines behavior for the unary - negation operator
Implementing __neg__
Basic implementation of __neg__ in a class.
python
class Example: def __neg__(self): return "Example __neg__" obj = Example() print(obj)
__neg__ defines behavior for the unary - negation operator. Implementing it lets you customize how Python interacts with your objects.
__neg__ in action
Seeing __neg__ called by Python's built-in operations.
python
# How Python calls __neg__ automatically class Demo: def __init__(self, value): self.value = value def __neg__(self): print(f"__neg__ was called!") return self d = Demo(42) # This triggers __neg__: print(d)
Python automatically calls __neg__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground