简体   繁体   中英

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

Person(moneyInTheBank = 90)

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

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__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM