Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subtract value from class instance attribute

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Person(moneyInTheBank = 90)

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

>Solution :

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__

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading