Rounding in Custom Classes
When working with custom classes in Python, you may need to define your own rounding behavior. This can be achieved by implementing the __round__()
method in your class. The __round__()
method is called when the built-in round()
function is used on an instance of your class.
Here's an example of a custom class that implements rounding:
class Currency:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __round__(self, ndigits=0):
return Currency(round(self.amount, ndigits), self.currency)
def __str__(self):
return f"{self.amount:.2f} {self.currency}"
## Example usage
money = Currency(12.345, "USD")
print(round(money, 1)) ## Output: 12.35 USD
In this example, the Currency
class has an __init__()
method that takes an amount and a currency, and a __round__()
method that performs the rounding operation. The __round__()
method takes an optional ndigits
argument, which specifies the number of decimal places to round to.
When the round()
function is called on an instance of the Currency
class, the __round__()
method is automatically invoked, and a new Currency
object with the rounded amount is returned.
You can also define more complex rounding behavior in your custom classes, such as rounding to the nearest multiple of a specific value, or rounding up or down based on certain criteria.
classDiagram
class Currency {
-amount: float
-currency: str
+__init__(amount, currency)
+__round__(ndigits=0): Currency
+__str__(): str
}
By implementing custom rounding behavior in your classes, you can ensure that your objects are always rounded in a way that is consistent with your application's requirements.