【问题标题】:Python - Calling Variable From (Static) Method of One Class in Method of Another ClassPython - 在另一个类的方法中从一个类的(静态)方法调用变量
【发布时间】:2017-03-23 13:13:23
【问题描述】:

我正在 PyQt 中制作 GUI,需要将我的脚本的图形创建类和方法与其分析类方法连接起来。我已经尝试通过简单地从图形方法中调用分析方法(如下所示)来做到这一点,但这会导致“未定义全局名称'UsersPerPlatform'”错误,因此这显然不会从另一个中提取字典方法。

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!'

我想避免将这两种方法合二为一,因为这会打乱我的文件,但如有必要,我会考虑更改静态方法的方法类型。

【问题讨论】:

  • 在您上面的代码中,您的静态方法有两个返回,一个接一个,并且没有关于UsersPerPlatform 来自何处的信息。它应该是您的静态方法的返回值吗? / 请把剩下的相关代码清理一下/填写好吗?
  • 该信息与问题无关。所有相关的是,是的,静态方法返回两个字典。
  • @JonathanConnell 不,它返回单个字典。第二个返回语句是无法访问的代码。
  • 没错!此外,在您的情况下,您没有捕获返回值:UsersPerPlatform = Analytics.UserPerCountryOrPlatform()
  • 请记住UsersPerPlatformUsersPlatformPie 中不存在,因此您的for 会尝试访问不存在的变量。如果您从UsersPerCountryOrPlatform 返回的结果正常,请将Analytics.UsersPerCountryOrPlatform() 放入变量中。

标签: python class methods pyqt static-methods


【解决方案1】:

您无法从被调用函数访问本地命名空间 - 但您可以轻松访问任何被调用函数的返回值。

class Analytics:
    @staticmethod
    def UsersPerCountryOrPlatform():
        ...
        return UsersPerCountry, UsersPerPlatform

class UsersPlatformPie:
    def compute_figure(self):
        myUsersPerCountry, myUsersPerPlatform = Analytics.UsersPerCountryOrPlatform()
        print(myUsersPerCountry)
        print(myUsersPerPlatform)

【讨论】:

  • 我只想要 Analytics.UsersPerCountryOrPlatform() 返回的 UsersPerPlatform 部分中的 p、c(即没有 UsersPerCountry 数据)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
相关资源
最近更新 更多