Currency Converter
Challenge: Currency Converter Class with Accessors & Mutators
Objective: Create a CurrencyConverter class that converts an amount from a foreign currency to your local currency, using accessor and mutator methods.
1. Class Properties (Instance Variables)
currency: The name of the foreign currency (e.g., “USD”, “AUD”).rate: The conversion rate of that currency to your local currency (e.g., 1 USD = 70 INR).
2. Class Methods
__init__(self, currency, rate)- The constructor that takes the initial
currencyname and conversionrate. - Initializes the object’s properties with these values.
- The constructor that takes the initial
- Accessor Methods (Getters)
get_currency(self)- Returns the current currency name.
get_rate(self)- Returns the current conversion rate.
- Mutator Methods (Setters)
set_currency(self, new_currency)- Changes the currency name to
new_currency.
- Changes the currency name to
set_rate(self, new_rate)- Changes the conversion rate to
new_rate.
- Changes the conversion rate to
- Core Functionality Method
convert(self, amount)- Takes an
amountin the foreign currency. - Formula:
amount * rate - Returns the converted value in your local currency.
- Takes an
3. Task Instructions
- Write the
CurrencyConverterclass with the constructor, two getters, two setters, and theconvertmethod. - Create an object of the class (e.g., for “USD” with a rate of 70).
- Test the class by:
- Using the
convertmethod to convert an amount (e.g., 100 USD). - Using the setter methods to change the currency and rate (e.g., to “AUD” with a rate of 50).
- Using the getter methods to check the new currency and rate.
- Calling the
convertmethod again with a new amount to verify the updated conversion works.
- Using the
class CurrencyConverter:
def __init__(self, name, rate):
self.currency = name
self.rate = rate
def get_currency(self):
return self.currency
def get_rate(self):
return self.rate
def set_currency(self, name):
self.currency = name
def set_rate(self, rate):
self.rate = rate
def convert(self, amount):
return self.currency + ' conversion is ' + str(self.rate * amount)
cc = CurrencyConverter('USD', 70)
print(cc.convert(100))
cc.set_currency('AUD')
cc.set_rate(50)
print(cc.convert(100))