OOP Python add some attribute to the base class?
I am learning OOP with python .trying with small console application Stock
class Stock(object):
def __init__(self, stockName, stockLimit, inStock, rentPrice):
self.stockName = stockName # private
self.stockLimit = stockLimit # private
self.inStock = inStock # private
self.rentPrice = rentPrice # private
def inputStock(self, nProduct):
if(nProduct >= (self.stockLimit - self.inStock)):
self.inStock = self.stockLimit
else:
self.inStock += nProduct
def invoice(self, nDay):
return self.rentPrice * nDay
class StockProduct(Stock):
def __init__(self, factor):
# the base-class constructor:
Stock.__init__(self, stockName, stockLimit, inStock, rentPrice)
self.factor = factor # Extra for this stock
def invoice(self, nDay):
return Stock.invoice(self, nDay) * self.factor
class StockMaterial(Stock):
def __init__(self,factor):
# the base-class constructor:
Stock.__init__(self, stockName, stockLimit, inStock, rentPrice)
self.factor = factor # Extra开发者_运维百科 for this stock
def invoice(self,nDay):
return Stock.invoice(self, nDay)*self.factor
if __name__ == "__main__":
N = nDay = 0
myStock = Stock("stock111", 500, 200, 400000)
N = float(raw_input("How many product into stock: "+str(myStock.stockName)+" ? "))
myStock.inputStock(N)
nDay = int(raw_input("How many days for rent : "+str(myStock.stockName)+" ? "))
print "Invoice for rent the stock: "+str(myStock.stockName)+ " = "+ str(myStock.invoice(nDay))
StockProduct = StockProduct("stock222",800, 250, 450000, 0.9)
N = float(raw_input("How many product into stock: "+str(StockProduct.stockName)+" ? "))
StockProduct.inputStock(N)
nDay = int(raw_input("How many days for rent : "+str(StockProduct.stockName)+" ? "))
print "Invoice for rent the stock: "+str(StockProduct.stockName)+ " = "+ str(StockProduct.invoice(nDay))
I have two questions:
- with my method
invoice
, how Can I do method overloading in python ? I added some attribute in the child I got the following error message:
StockProduct = StockProduct("stock222",800, 250, 450000, 0.9) TypeError error: __init__() takes exactly 2 arguments (6 given)
What I should do here?
Anybody can help me please?
Thank in advance
The overloaded
invoice
in the derived class should work fine.Your base class constructor needs to have all the parameters, so :
class StockProduct(Stock): def __init__(self, stockName, stockLimit, inStock, rentPrice, factor): # the base-class constructor: Stock.__init__(self, stockName, stockLimit, inStock, rentPrice) self.factor = factor def invoice(self, nDay): return Stock.invoice(self, nDay) * self.factor
1 - Yes, you can do method overloading in python.
2 - Your child class changed the method signature. You should declare it as
def __init__(self, stockName, stockLimit, inStock, rentPrice, factor):
if you want to construct it with all the arguments from the parent class plus some extra.
精彩评论