How can I overload the unary negative (minus) operator in Python?

Question:

class Card():
    def __init__(self, val):
        self.val = val

c = Card(1)
d = -c

I expect d to be a Card object and d.val to be -1. How I can do that?

Asked By: max yue

||

Answers:

It sounds like you want the unary minus operator on Card to return a new card with the value negated. If that’s what you want, you can define the __neg__ operator on your class like this:

class Card:
    def __init__(self, val):
        self.val = val
    def __neg__(self):
        return Card(-self.val)

__neg__ is included in the list of methods that can be overridden to customise arithmetic operations in the docs: emulating numeric types.

Answered By: khelwood
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.