简体   繁体   中英

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 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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