简体   繁体   中英

Passing data between functions, using Main()

I am trying to pass data from one function to another, with in a class and print it. I am unsuccessful and keep getting errors. Error at bottom for help. Thanks in advance.

class Stocks(object):
def __init__(self, name):
    self.name = name
    print(name)

def Get_Data(self):
    #self.data2 = data2
    #print(self.name)
    data2 = web.get_data_yahoo(self.name,data_source='yahoo',start=start_date,end=end_date)['Adj Close']
    #print(data2)
    #data2.plot(figsize=(10,5))
    #plt.show()
    return data2

def Main(self, Get_Data):

    x = Stocks(Get_Data())
    print(x)
    #data2.plot(figsize=(10,5))
    #plt.show()

z = Stocks('GE')
z.Get_Data()
z.Main()


error:
TypeError: Main() missing 1 required positional argument: 'Get_Data'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-162-91f08c3bdb57> in <module>()
     32 z = Stocks('GE')
     33 z.Get_Data()
---> 34 z.Main()
TypeError: Main() missing 1 required positional argument: 'Get_Data'

A function definition includes a list of parameters, that have to be matched by the arguments passed in when the function is called.

So, if you define Main to take a Get_Data parameter, you have to pass something an argument to be the value for Get_Data whenever you call it.

But you're not passing anything at all, hence the TypeError .


Since Main expects to call its Get_Data with no arguments, it has to be something callable with no arguments. The bound method z.Get_Data fits the bill, so you could do this:

z.Main(z.Get_Data)

But that's a very weird design.


More likely, you didn't want to add such a parameter in the first place:

def Main(self):

… because what you want Main to do is call Get_Data on itself, not to call some arbitrary thing the caller passed in:

x = Stocks(self.Get_Data())
print(x)

Except that you probably didn't want to construct a new Stocks value here, with the result of z.Get_Data() as the name, you just wanted to use the result of z.Get_Data() . So:

x = self.Get_Data()
print(x)

The error is quite obvious: you declared Main to have a parameter, Get_Data (ignoring the self pointer that all class members implicitly have/pass). When you call z.Main() you are not passing that parameter, so the interpreter asks you to fill this gap.

You probably meant something like:

def Main(self):
    x = Stocks(self.Get_Data())
    print(x)

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