简体   繁体   English

创建可访问每一层变量的多层Python类

[英]Creating multi-layered Python classes with access to variables within each layer

In Python 2.7, I'm trying to create classes within classes (and so on), like for example: 在Python 2.7中,我试图在类中创建类(依此类推),例如:

class Test(object):

    def __init__(self, device_name):
        self.device_name = device_name

    class Profile(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2

    class Measurement(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2    

Using this layering to create objects, I need to be able to assign and access any variable in any layer, like for example: 使用此分层来创建对象,我需要能够分配和访问任何层中的任何变量,例如:

test1 = Test("Device_1")
Test.Profile(test1, 10, 20)
Test.Measurement(test1, 5, 6)

print test1.Profile.x1
print test1.Measurement.x1 

It should also be noted that I need to load the classes with data taken from a text file. 还应注意,我需要使用从文本文件获取的数据加载类。

I thought that using classes would be the best way of achieving this but I'd be happy to hear any other ideas. 我认为使用类是实现这一目标的最佳方法,但我很高兴听到其他想法。

My version/solution class scopes : 我的版本/解决方案类范围

class Test(object):

    def __init__(self, device_name):
        self.device_name = device_name

    class Profile(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2

    class Measurement(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2

test1 = Test("Device_1")
prof = test1.Profile(10, 20)
meas= test1.Measurement(5, 6)

print (prof.x1)
print (meas.x1) 

>>> 10
>>> 5

Though I don't know why you want nested classes, this will do exactly as you want. 尽管我不知道为什么要嵌套类,但这将完全按照您的意愿进行。 If you look at the example, be sure to note the change in syntax. 如果查看示例,请确保注意语法的变化。

class Test(object):
    class Profile(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2

    class Measurement(object):
        def __init__(self, x1, x2):
            self.x1 = x1
            self.x2 = x2

    def __init__(self, device_name):
        self.device_name = device_name
        self.profile = None
        self.measurement = None

    def make_profile(self, a, b):
        self.profile = self.Profile(a, b)

    def make_measurement(self, a, b):
        self.measurement = self.Measurement(a, b)

test1 = Test("Device_1")
test1.make_profile(10, 20)
test1.make_measurement(5, 6)

print (test1.profile.x1)
print (test1.measurement.x1)

Output: 输出:

10
5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM