Jonathan Connell Jonathan Connell -4 years ago 133
Python Question

Python - Calling Variable From (Static) Method of One Class in Method of Another Class

I am making a GUI in PyQt and need to connect the graphic creation classes and methods of my script with its analytics class methods. I've tried doing this by simply calling the analytics method from within the graphic method (as seen below) but this results in a "global name 'UsersPerPlatform' is not defined" error so this clearly doesn't pull the dictionary from the other method.

class Analytics():

def UsersPerCountryOrPlatform():
return UsersPerCountry
return UsersPerPlatform #both are dictionaries

class UsersPlatformPie(MyMplCanvas): #irrelevant parent

def compute_figure(self):
Analytics.UsersPerCountryOrPlatform() #running function to return UsersPerPlatform
for p, c in UsersPerPlatform:
print 'If I could access the UsersPerPlatform dictionary I would plot something!'

I'd like to avoid combining the two methods into one as this will disorganise my file but I will consider changing the method type of the static method if necessary.

Answer Source

You cannot access local namespace from called function - but you can easily access return value from any called function.

class Analytics:
    def UsersPerCountryOrPlatform():
        return UsersPerCountry, UsersPerPlatform

class UsersPlatformPie:
    def compute_figure(self):
        myUsersPerCountry, myUsersPerPlatform = Analytics.UsersPerCountryOrPlatform()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download