简体   繁体   English

从 class 属性创建列表 - Python

[英]Creating a list from the class attributes - Python

I was wondering if someone could elaborate on exactly why creating a new list out of the two attributes passed in the class returns a "NoneType"?我想知道是否有人可以详细说明为什么从 class 中传递的两个属性中创建一个新列表会返回“NoneType”?

class Finance:
    
    def __init__(self, market = '^GSPC', tickers = []):
        
        self.market = market
        self.tickers = tickers
        self.final_list = self.tickers.insert(0,self.market)


x = Finance(tickers = ['AMZN', 'AAPL'])

type(x.final_list)

I have found a way to create a list of these two by using我找到了一种通过使用创建这两个列表的方法

[value for value in self.__dict__.values()]

but I just feel like there should be a more elegant way of doing it.但我只是觉得应该有一种更优雅的方式来做到这一点。

Well, i have tried using Python 3.10 but I'm pretty sure that the insert list method is in place and doesn't return a value.好吧,我已经尝试使用 Python 3.10,但我很确定插入列表方法已经到位并且不会返回值。 So my advice is to change the code this way:所以我的建议是这样更改代码:

import copy
class Finance:
    def __init__(self, market = '^GSPC', tickers = []):
        self.market = market
        self.tickers = tickers
        self.tickers.insert(0,self.market)
        self.final_list = copy.deepcopy(self.tickers)

Now you have a deep copy of the modified list in the variable instance final_list现在您在变量实例 final_list 中拥有修改列表的深层副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM