Jak ustawić precyzję dla typu Decimal w obrębie całej klasy?

0

Cześć

Mam taki kod

class Money:
    def __init__(self, amount: Decimal, currency: Currency, precision: int = 2):
        self.amount = amount
        self.currency = currency

    def __str__(self):
        return f"{self.amount} {self.currency.symbol}"

    def __repr__(self):
        return f"Money({self.amount!r}, {self.currency!r})"

Jak mogę ustawić precyzję dla zmiennej amount tak aby tylko w instancjach klasy Money precyzja wynosiła tyle ile jest ustawione w zmiennej precision?

Z góry dzięki

1
round()

Albo f-stringi -> f'{amount:.{precision}f}'

0

A jak mam taką zdefiniowaną metodę w klasie to co zrobić? Użyć menedżera kontekstu i przypisać ctx.prec = self.prcision w metodach przeciążających operatory?

def __add__(self, other):
    if self.currency != other.currency:
        raise ValueError("can't add two Money instances:"
                         "different currency property")
    return Money(self.amount + other.amount, self.currency)

def __sub__(self, other):
    if self.currency != other.currency:
        raise ValueError("can't subtract two Money instances:"
                         "different currency property")
    return Money(self.amount - other.amount, self.currency)
1

Twój problem jest taki ze metoda np "add" dodaje wartosci zwraca ci default wartosc z klasy. Musisz dopisac atrybut precision

def __add__(self, other):
    if self.currency != other.currency:
        raise ValueError("can't add two Money instances:"
                         "different currency property")
    return Money(self.amount + other.amount, self.currency, self.precision)

def __sub__(self, other):
    if self.currency != other.currency:
        raise ValueError("can't subtract two Money instances:"
                         "different currency property")
    return Money(self.amount - other.amount, self.currency, self.precision)

dopisałem self.precision do obiektu

a teraz dluzsze tłumaczenie jesli chce ci sie czytac xD
Jak dodajesz dwa obiekty Money to tworzy ci nowy obiekt, który ma atrybut precision ustawiony taki jaki masz zadeklarowany w klasie (czyli 2)

Przykład:

from decimal import Decimal


class MyMoney:
    def __init__(self, amount: Decimal, precision: int = 2):
        self.amount = amount
        self.precision = precision

    def __str__(self):
        return f"{self.amount:.{self.precision}f}"

    def __repr__(self):
        return f"({self.__class__.__name__ },{self.amount!r},{self.precision!r})"

    def __add__(self, other):
        return MyMoney(self.amount + other.amount)

    # default precision pozostaje 2
    def __sub__(self, other):
        return MyMoney(self.amount - other.amount)

    # default precision jest taki jaki zadeklarowales przy tworzeniu instancji
    def __mul__(self, other):
        return MyMoney(self.amount * other.amount, self.precision)

print(" a3 example ---")

# stworz obiekty z default precision 3
a3 = MyMoney(1.666, 3)
b3 = MyMoney(1.491, 3)

print(a3)
print(b3)
print(repr(a3))
print(repr(b3))


# jak dodajesz albo mnozysz tyworzy ci nowy obiekt z tymi samymy atrybutami ustawonymi as default 
# czyli precyzja nadal bedzie 2 bo klasa ma precision atrybut ustawiony na 2 jako twoje default

s3 = a3 + b3
s4 = a3 * b3
print(" dzialania", s3, s4)
print("/\ jak widzisz sa różne atrybuty precision") 

# musisz zmien precyzje dla instacji jak dodajesz ..
print(s3, "before")
s3.precision = 3
print(s3, "after")

# nic nie musisz robic precision pozostaje 
print(s4, "Multiplication")

1 użytkowników online, w tym zalogowanych: 0, gości: 1