Home > Back-end >  How to call an instance inside class methods?
How to call an instance inside class methods?

Time:08-27

class Purse:
    def __init__(
        self,
        owner,
        currency="USD",
    ):
        if currency not in ("EUR", "USD"):
            raise ValueError
        self.owner = owner
        self.__money = 0.00  
        self.currency = currency

        def withdraw_money(self, howmany):
    if self.__money - howmany < 0:
        raise ValueError("not enough balance")
    self.__money = self.__money - howmany
    return howmany

    def add_money(self, howmany): 

#How to check if instance attribute != another_instance attribute to raise ValueError?

        self.__money = self.__money   howmany
        return howmany

)

#So

name1.add_money(name2.withdraw_money(value))

should raise ValueError, if name1.currency, for instance is "USD" and name2.currency is "EUR"

CodePudding user response:

You should create a separate transfer_money() method for this. It will take the destination instance, and you can compare the currencies.

def transfer_money(dest, howmany):
    if self.currency != dest.currency:
        raise ValueError('source and destination use different currencies')
    dest.add_money(self.withdraw_money(howmany))
  • Related