请查看以下代码段。你可以理解我想要做的事情。 PairTwo类的vlan_start必须从PortOne的值派生。我该怎么做?
>>> class G8032:
... class PairOne:
... vlan_start = 1101
... vlan_count = 600
... class PairTwo:
... vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count
... vlan_count = 400
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in G8032
File "<stdin>", line 6, in PairTwo
NameError: name 'G8032' is not defined
>>>
编辑:
我在G8032
中尝试了G8032.PairOne.vlan_***
。它仍然无法运作。
答案 0 :(得分:2)
不要嵌套这些课程。执行行vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count
时,G8032
类尚未完全定义。
如果您绝对需要支持您在评论中提到的语法(x = G8032.PairOne.vlan_start
),那么可以(但可能不应)使用以下代码:
class PairOne:
vlan_start = 1101
vlan_count = 600
class PairTwo:
vlan_start = PairOne.vlan_start + PairOne.vlan_count
vlan_count = 40
class G8032:
PairOne = PairOne
PairTwo = PairTwo
print(G8032.PairOne.vlan_start)
print(G8032.PairTwo.vlan_start)
# 1101
# 1701
答案 1 :(得分:1)
为什么不做这样的事情 -
class G8032:
pass
class PairOne:
vlan_start = 1101
vlan_count = 600
class PairTwo:
p = PairOne()
vlan_start = p.vlan_start + p.vlan_count
vlan_count = 400
if __name__ == "__main__":
g = G8032()
g.PairOne = PairOne()
g.PairTwo = PairTwo()
您可能会发现此主题很有趣 - Nested classes' scope?
答案 2 :(得分:0)
如果您需要上述语法,可以使用:
class G8032:
PairOne = type('PairOne', (object,), dict({'vlan_start': 1101, 'vlan_count': 600}))
PairTwo = type('PairTwo', (object,), dict({'vlan_start': PairOne.vlan_start + PairOne.vlan_count, 'vlan_count': 400 }))
print (G8032.PairOne.vlan_start)
>>> 1101