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 currency name and conversion rate.
    • Initializes the object’s properties with these values.
  • 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.
    • set_rate(self, new_rate)
      • Changes the conversion rate to new_rate.
  • Core Functionality Method
    • convert(self, amount)
      • Takes an amount in the foreign currency.
      • Formula: amount * rate
      • Returns the converted value in your local currency.

3. Task Instructions

  1. Write the CurrencyConverter class with the constructor, two getters, two setters, and the convert method.
  2. Create an object of the class (e.g., for “USD” with a rate of 70).
  3. Test the class by:
    • Using the convert method 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 convert method again with a new amount to verify the updated conversion works.

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))

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *