如何在Python中向基类添加属性?

2 投票
2 回答
2184 浏览
提问于 2025-04-16 15:50

我正在用Python学习面向对象编程,正在尝试做一个小的控制台应用程序,叫做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)
    

我该怎么做呢?

有没有人能帮帮我?

提前谢谢大家!

2 个回答

2

1 - 是的,你可以在Python中使用方法重载。

2 - 你的子类改变了方法的签名。你应该这样声明:

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

如果你想在构造时使用父类的所有参数 再加上 一些额外的参数。

6
  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
    

撰写回答