OOP Python为基类添加了一些属性?

时间:2011-04-15 20:20:22

标签: python oop

我正在学习使用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))

我有两个问题:

  1. 使用我的方法invoice,如何在python中进行方法重载?
  2. 我在孩子中添加了一些属性,我收到以下错误消息:

    StockProduct = StockProduct("stock222",800, 250, 450000, 0.9)
    TypeError
    
    error: __init__() takes exactly 2 arguments (6 given)
    
  3. 我应该在这做什么?

    有人可以帮我吗?

    提前感谢

2 个答案:

答案 0 :(得分:3)

  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
    

答案 1 :(得分:2)

1 - 是的,你可以在python中进行方法重载。

2 - 您的子类更改了方法签名。你应该声明它为

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

如果你想用父类加上的所有参数来构造它,那么可以使用