【问题标题】:Alternative to nested classes?替代嵌套类?
【发布时间】:2015-07-13 10:05:53
【问题描述】:

我正在使用嵌套类来构造我的数据和数据特定函数(无法在代码 sn-p 中正确缩进,抱歉):

class test:
    class AA:
        def __init__(self):
            self.name = "ZZ-top"
            self.flag = False
        def reset(self):
            self.name = "AArdvark"
            self.flag = True
    class BB:
        def __init__(self):
            self.num = 11
        def checker(self):
            if self.num > 10:
                test.AA.name = "Toasty"                     
    def __init__(self):
        self.AA = self.AA()
        self.BB = self.BB()

对我来说,这是按类别隔离数据的最简洁、最简单的方法。我经常有来自不同来源的相同数据,并希望将其表示出来。例如。 data.image.latitude 和 data.csv.latitude。我还想拥有从多个类获取或设置数据的函数。例如:检查功能。

问题是 python 似乎不喜欢嵌套类。我遇到了泡菜的麻烦(不能泡菜类'test.BB.num'。这似乎是一个常见的泡菜/嵌套类问题)并且一些需要相邻类信息的函数不起作用。我想我必须放弃嵌套类。

什么是构建这些数据的python'esque正确方法?我应该只拥有一个包含所有功能的大类(self.AA_timeofday ... self.ZZ_timeofday)还是有更好的东西?

【问题讨论】:

    标签: python class nested pickle


    【解决方案1】:

    很少需要嵌套类,除了将类的名称包装在另一个命名空间中并打破酸洗之外,在功能上没有区别。

    只需将类放在模块的全局级别:

    class AA:
        def __init__(self):
            self.name = "ZZ-top"
            self.flag = False
        def reset(self):
            self.name = "AArdvark"
            self.flag = True
    
    class BB:
        def __init__(self):
            self.num = 11
        def checker(self):
            if self.num > 10:
                test.AA.name = "Toasty"   
    
    class test:                  
        def __init__(self):
            self.AA = AA()
            self.BB = BB()
    

    【讨论】:

    • 是的,就是这样。我不敢相信我错过了的简单解决方案。
    • 如何调用checker()函数?尝试运行时,我不断收到 AttributeError。
    • @MehrdadMehraban:没有详细说明您如何创建实例或您尝试调用的实例,或者属性错误可能是什么,我无能为力。
    猜你喜欢
    • 2018-09-02
    • 2011-03-27
    • 2013-07-20
    • 2020-12-22
    • 2014-05-08
    • 2019-02-28
    • 2011-07-10
    相关资源
    最近更新 更多