Python - 从一个 Class 的(静态)方法调用另一个 Class 的方法中的变量
Python - Calling Variable From (Static) Method of One Class in Method of Another Class
我正在 PyQt 中制作 GUI,需要将我脚本的图形创建 classes 和方法与其分析 class 方法连接起来。我尝试通过简单地从图形方法中调用分析方法(如下所示)来执行此操作,但这会导致 "global name 'UsersPerPlatform' is not defined" 错误,因此这显然不会从其他方法中提取字典。
class Analytics():
@staticmethod
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!'
我想避免将这两种方法合二为一,因为这会打乱我的文件,但我会考虑在必要时更改静态方法的方法类型。
您无法从被调用函数访问本地命名空间 - 但您可以从任何被调用函数轻松访问 return 值。
class Analytics:
@staticmethod
def UsersPerCountryOrPlatform():
...
return UsersPerCountry, UsersPerPlatform
class UsersPlatformPie:
def compute_figure(self):
myUsersPerCountry, myUsersPerPlatform = Analytics.UsersPerCountryOrPlatform()
print(myUsersPerCountry)
print(myUsersPerPlatform)
我正在 PyQt 中制作 GUI,需要将我脚本的图形创建 classes 和方法与其分析 class 方法连接起来。我尝试通过简单地从图形方法中调用分析方法(如下所示)来执行此操作,但这会导致 "global name 'UsersPerPlatform' is not defined" 错误,因此这显然不会从其他方法中提取字典。
class Analytics():
@staticmethod
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!'
我想避免将这两种方法合二为一,因为这会打乱我的文件,但我会考虑在必要时更改静态方法的方法类型。
您无法从被调用函数访问本地命名空间 - 但您可以从任何被调用函数轻松访问 return 值。
class Analytics:
@staticmethod
def UsersPerCountryOrPlatform():
...
return UsersPerCountry, UsersPerPlatform
class UsersPlatformPie:
def compute_figure(self):
myUsersPerCountry, myUsersPerPlatform = Analytics.UsersPerCountryOrPlatform()
print(myUsersPerCountry)
print(myUsersPerPlatform)