创建每一层内多层Python类可以访问变量
在Python 2.7,我试图创建类中的类(等),例如像:创建每一层内多层Python类可以访问变量
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")
Test.Profile(test1, 10, 20)
Test.Measurement(test1, 5, 6)
print test1.Profile.x1
print test1.Measurement.x1
还应当指出的是,我需要从一个文本文件中获取的数据来加载类。
我认为使用类将是实现这一目标的最佳方式,但我很乐意听到任何其他想法。
我的版本/解决方案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
虽然我不知道为什么你要嵌套类,只要你想这会做完全。如果你看一下这个例子,一定要注意语法的变化。
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)
输出:
10
5
真的需要额外的方法吗? –
在你的解决方案中,你创建了单独的对象,而我的所有对象都在同一个对象中。理论上你可以传入原始构造函数中的所有参数,但似乎并不像他想要的那样。 – Navidad20
你有@property这种情况下,但最终我们都创建对象.... –
为什么你创建的类中的类? –
你的问题是什么? –
您可以将Profile和Measurement类分开文件,并从Test类返回这些类的实例。你不需要做那个嵌套。 – emKaroly