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?
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With