2011-04-15 71 views
0

我在學習使用Python與小型控制檯應用程序.trying OOP StockOOP Python將一些屬性添加到基類中?

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

我有兩個問題:

  1. 用我的方法invoice,我該怎麼辦方法重載的蟒蛇?
  2. 我加在孩子的一些屬性,我得到了以下錯誤消息:

    StockProduct = StockProduct("stock222",800, 250, 450000, 0.9) 
    TypeError 
    
    error: __init__() takes exactly 2 arguments (6 given) 
    

我應該做的是什麼?

有人可以幫我嗎?

預先提前感謝

回答

2
  1. 派生類中的重載invoice應該正常工作。

  2. 你的基類的構造函數需要有所有的參數,所以:

    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 
    
+0

是高帶寬,謝謝。 – kn3l 2011-04-15 20:44:41

2

1 - 是的,你可以在python中做方法重載。

2 - 您的孩子班級更改了方法簽名。如果你想從父類一些額外的所有的參數來構建它,你應該把它聲明爲

def __init__(self, stockName, stockLimit, inStock, rentPrice, factor):