You need to create an instance of the Currency object before using it and calling its methods. The way you have it done, you are trying to call a static method of the Currency class in the very last line of posted code (and it probably gives you an error stating that getconversionrate() expects 2 params, but only 1 given).
class Currency(object):
def __init__(self, currency, conversion_rate):
self.currency = currency
self.conversion_rate = conversion_rate
def getconversionrate(self, currency):
return self.conversion_rate
class Stock_Detail(object):
def __init__(self, item, cost, local_cost, currency):
self.item = item
self.local_cost = local_cost
self.currency = currency
# Create an instance of Currency object.
# The constructor (the __init__ method) accepts 2 parameters.
# The 1.2 conversion rate is made up, you pass your own (correct) one.
currencyObject = Currency(currency, 1.2)
self.cost = self.local_cost * currencyObject.getconversionrate(self.currency) Here are couple things you might want to consider:
1) Why pass the cost to Stock_Detail constructor, if you are calculating that value and not using what is passed in?
2) Why not pass the Currency object into the Stock_Detail constructor? That way, if you have many Stock_Detail objects, the same Currency object can be reused.
If I understand what you are trying to do, maybe the following code will help:
# This class describes the currency in terms of its name and conversion rate.
class Currency(object):
def __init__(self, name, rate):
self.name = name
self.rate = rate
# This class describes a Stock by its name/item and price (local_cost in your code).
class Stock(object):
def __init__(self, item, price):
self.item = item
self.price = price
# Returns the cost of this Stock in given currency.
def getcost(self, currency):
return self.price * currency.rate
### Here is the code that uses classes defined above.
# Create Currency objects (I don't know the exact rates).
c1 = Currency("Canadian Dollars", 0.9)
c2 = Currency("Russian Rubles", 2.5)
# Couple stocks
s1 = Stock("Microsoft", 30.5)
s2 = Stock("IBM", 25.8)
s3 = Stock("Sun", 35.0)
# Print original prices of stocks
print s1.price, s2.price, s3.price
# Print cost in Canadian Dollars
print s1.getcost(c1), s2.getcost(c1), s3.getcost(c1)
# Print cost in Russian Rubles
print s1.getcost(c2), s2.getcost(c2), s3.getcost(c2)