Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 586
max yue Avatar asked Aug 02 '17 07:08

max yue


People also ask

What is unary minus operator in Python?

The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .

How do you overload the unary operator?

You can overload a prefix or postfix unary operator by declaring a nonstatic member function taking no arguments, or by declaring a nonmember function taking one argument. If @ represents a unary operator, @x and x@ can both be interpreted as either x.


1 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 here: https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types

like image 128
khelwood Avatar answered Oct 20 '22 12:10

khelwood