【问题标题】:Getting only one attrubute when passing an array of class objects?传递一组类对象时只获得一个属性?
【发布时间】:2021-09-09 08:56:26
【问题描述】:

我正在尝试根据市值过滤股票,并且我想将股票列表设置为类对象,因此我将带有股票代码的数组作为对象传递。但是当我期望它返回两个布尔值(因为有两只股票)时,我只得到一个“假”。

如何修改以下代码,以便获取列表中所有项目的 cond_1 属性。 (例如 AAPL.cond_1 = False,GOOG.cond_1 = False)?

top_gainer_list = ['AAPL', 'GOOG']


class gainers():
    def __init__(self, cond_1):
        self.cond_1 = cond_1


    def filter_marketCap(self):
        backup_list1 = []
        iexresponse = requests.get(
            "https://cloud.iexapis.com/stable/stock/market/batch?symbols={}&types=quote&token=APIKEY".format(
                ','.join(top_gainer_list)))
        data = iexresponse.json()
        for ticker in top_gainer_list:
            marketCap = int(data[ticker]['quote']['marketCap'])
            if 10000000 <= marketCap <= 200000000:
                self.cond_1 = True
            else:
                self.cond_1 = False


top_gainer = gainers(top_gainer_list)
top_gainer.filter_marketCap()
print(top_gainer.cond_1)

【问题讨论】:

    标签: python arrays class object oop


    【解决方案1】:

    看-

    self.cond_1 = False
    
    
    top_gainer = gainers(top_gainer_list)
    top_gainer.filter_marketCap()
    print(top_gainer.cond_1)
    

    您正在打印self.cond_1。所以只有后面的值被打印出来。要解决此问题,请在方法本身中使用 print 语句 -

    if 10000000 <= marketCap <= 200000000:
                    print(True)
                else:
                    print(False)
    

    只需如图所示更改行,您将获得 2 个结果。 不要再次使用打印下来。只需调用方法 -

       top_gainer = gainers(top_gainer_list)
       top_gainer.filter_marketCap()
    

    【讨论】:

    • 当我调用函数时,有没有办法可以获取列表中所有项目的 cond_1 值?
    • 我没听懂你。这将打印列表中的所有项目
    猜你喜欢
    • 2013-08-23
    • 2016-08-05
    • 2013-04-12
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多