Subtract value from class instance attribute

Question:

Basic question. Say I have the class:

@dataclass
class Person:
   
    moneyInTheBank: float

And i want to implement that when I do something like:

Person(100) - 10

I get

Person(moneyInTheBank = 90)

How is that done easily? Magic Methods? Getters and Setters?

Asked By: Jailbone

||

Answers:

You can use __sub__ magic method:

from dataclasses import dataclass

@dataclass
class Person:
    moneyInTheBank: float

    def __sub__(self, other):
        return Person(self.moneyInTheBank - other)

p = Person(100)
print(p - 10)

Prints:

Person(moneyInTheBank=90.0)

EDIT:
If you want to modify the object, try using this:

def __sub__(self, other):
    self.moneyInTheBank -= other
    return self

To make it work with -=, use __isub__

Answered By: Fastnlight
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.