Home > database >  Subtract value from class instance attribute
Subtract value from class instance attribute

Time:12-08

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?

CodePudding user response:

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__

  • Related