[英]OOP Python add some attribute to the base class?
我正在使用python學習OOP。嘗試使用小型控制台應用程序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))
我有兩個問題:
invoice
,如何在python中進行方法重載? 我在孩子中添加了一些屬性,但收到以下錯誤消息:
StockProduct = StockProduct("stock222",800, 250, 450000, 0.9) TypeError error: __init__() takes exactly 2 arguments (6 given)
我應該在這里做什么?
有人可以幫我嗎?
預先感謝
派生類中超載的invoice
應該可以正常工作。
您的基類構造函數需要具有所有參數,因此:
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-是的,您可以在python中進行方法重載。
2-您的子類更改了方法簽名。 您應該將其聲明為
def __init__(self, stockName, stockLimit, inStock, rentPrice, factor):
如果要使用父類的所有參數以及其他一些參數來構造它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.