Python PNL OOP,如何使用来自另一个类的属性

时间:2017-07-21 16:02:19

标签: python oop

我打算设计一个跟踪我的股票账户盈亏的程序,然后我使用Python并希望以面向对象的方式解决它。

代码:

class PNL(object):
    stock_amount = {}
    def __init__(self,cash,position):
        self.cash = cash
        self.position = position

    def buy(self,Stock,amount):
        pass
    def sell(self,Stock,amount):
        pass
    def stock_amt(self,Stock):
        if Stock().symbol not in stock_amount:
            stock_amount[Stock().symbol] = 0
        else:
            return stock_amount


class Stock():
    def __init__(self,symbol,timestamp,price):
        self.symbol = symbol
        self.time = timestamp
        self.price = price

a = PNL(0,0)
APPL = []
APPL.append(Stock('APPL',0,10))
APPL.append(Stock('APPL',1,12))
a.stock_amt('APPL')
for stock in APPL:
    if stock.time == 0:
        print stock.price

但这不行,有人对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

首先你需要修改类PNL,当你用Stock声明方法作为它的参数/参数时,你最好选择另一个名字,或者用小写来写它以改变类Stock

只是认为你会为这些方法提供一个实例,不需要编写类型,顺便说一句,不需要通过执行Stock().symbol再次实例化方法中的类,你将给出一个实例,或者如果您愿意,直接使用属性符号。

此外,stock_amount可以存储为实例属性,如下所示:

class PNL(object):

    def __init__(self,cash,position):
        self.cash = cash
        self.position = position
        self.stock_amount = {}

    def buy(self,stock,amount):
        pass
    def sell(self,stock,amount):
        pass
    def stock_amt(self,stock):
        if stock.symbol not in self.stock_amount:
            self.stock_amount[stock.symbol] = 0
        else:
            return self.stock_amount

然后当你打电话给你的课程时,我想你想循环你已经建立的APPL列表(然后只需拨打a.stock_amt(stock_object_created)

a = PNL(0,0)
APPL = []
APPL.append(Stock('APPL1',0,10))
APPL.append(Stock('APPL2',1,12))

for stock in APPL:
    a.stock_amt(stock)
    if stock.time == 0:
        print stock.price
print a.stock_amount

#>>>10
#>>>{'APPL2': 0, 'APPL1': 0}