To customize the behavior of the negation operator
-x, override the
__neg__(self) dunder method in your class definition. Python internally calls
x.__neg__() to calculate the inverse (negation) of an object, i.e.,
-x. If the
__neg__() method is not defined, Python will raise a
To use the negation operator
-x on a custom object
x, define the
__neg__() “dunder” magic method that takes one argument: a reference to itself, called
self. You can then use attributes of the custom objects to determine the object’s negation. It can return any object but the convention is to return an object of the same type so that
-(-x) == x.
Let’s have a look at an example next.
In the following code, you create a Person object
alice with a string
name attribute set to
'alice'. The negation is simply the
name string in reverse order by using slicing with negative step size
class Person: def __init__(self, name): self.name = name def __neg__(self): return self.name[::-1] alice = Person('alice') print(-alice) # ecila
The negated object
-alice returns the attribute
'alice' in reverse order as defined in the
__neg__() method. However, this is not a clean way of using the
__neg__ dunder method. Instead, you should always return the same object (per convention) so that the inversion criterion is fulfilled, i.e.,
-(-x) == x assuming the equality dunder method is properly defined.
You can see a proper use in the following example:
class Person: def __init__(self, name): self.name = name def __neg__(self): return Person(self.name[::-1]) def __eq__(self, other): return self.name == other.name alice = Person('alice') print(-(-alice) == alice) # True
[Fixed] TypeError: bad operand type for unary –
If you attempt to use the unary operator
-x on an object
x that doesn’t define the
__neg__ dunder method, Python raises a
TypeError: bad operand type for unary.
class Person: def __init__(self, name): self.name = name alice = Person('alice') print(-alice)
Here’s the error message of this code snippet:
Traceback (most recent call last): File "C:\Users\...\code.py", line 8, in <module> print(-alice) TypeError: bad operand type for unary -: 'Person'
To fix this error, simply define the unary
__neg__() dunder method in the class definition of the object on which you attempt to call the negation operator
This is exemplified here:
class Person: def __init__(self, name): self.name = name def __neg__(self): return Person(self.name[::-1]) alice = Person('alice') neg_alice = -alice print(neg_alice.name) # ecila
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.