For loop inside a class object in Python [closed]

Solution for For loop inside a class object in Python [closed]
is Given Below:

I’m creating a class in Python and passing a list (simbolList) through a for loop (generating data from those stocks), however, I don’t seem to figure out the logic behind this just yet. Any suggestions?

In essence, I want to pass the symbolList through the for loop and for each symbol passed, retrieve the stock data and save it in a dictionary (data dict), but it doesn’t seem to be working

This is the code

class Stocks:
    symbolList = ["AMZN"]
    data = {}

    def __init__(self, symbolList):
        self.symbolList = symbolList
        self.data = data

    def symbol(self):
        for symbol in self.symbolList:
            self.data[symbol] = get_data(symbol)
        print(self.data)
Stocks.symbol() #yields an errors, missing 1 required positional argument self

You’re using both class and instance attributes; you probably don’t want to be doing that. Here’s the code using only instance attributes:

class Stocks:
    def __init__(self, symbolList):
        self.symbolList = symbolList
        self.data = {}

    def symbol(self):
        for symbol in self.symbolList:
            self.data[symbol] = get_data(symbol)
        print(self.data)

stocks = Stocks(["AMZN"])
stocks.symbol()

Note that the “missing self” error is because you’re trying to call an instance method on a class. The above code fixes this by creating an instance called stocks, which is what provides the self parameter when you call the symbol() method.

FWIW since the symbol method is actually loading data from an external source, for all the symbols, I might suggest naming it differently; you can also write it a bit more concisely with a dictionary comprehension.

class Stocks:
    def __init__(self, symbolList):
        self.symbolList = symbolList
        self.data = {}

    def load_symbol_data(self):
        self.data = {symbol: get_data(symbol) for symbol in self.symbolList}


stocks = Stocks(["AMZN"])
stocks.load_symbol_data()
print(stocks.data)