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?
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.
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?
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.