How can I overload the unary negative (minus) operator in Python?
class Card():
def __init__(self, val):
self.val = val
c = Card(1)
d = -c
I expect to d
be an object Card
while d.val
-1. How can i do this?
+3
max yue
source
to share
1 answer
It sounds like you want the unary minus operator on to Card
return a new map with a negative value. If you need it, you can define the operator __neg__
in your class like this:
class Card:
def __init__(self, val):
self.val = val
def __neg__(self):
return Card(-self.val)
__neg__
included in the list of methods that can be overridden to customize arithmetic operations here: https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
+10
khelwood
source
to share