gpt4 book ai didi

python - python中的对象索引

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:38 24 4
gpt4 key购买 nike

我在 python 中创建了以下对象

它创建一个类arc的对象,然后使用对象arc创建另一个对象网络

class Arc:
# Creates an object of class arc
def __init__(self, tailNode = 0, headNode = 0, lowerBound = 0, upperBound = 0, cost = 0):
self.tailNode = tailNode
self.headNode = headNode
self.lowerBound = lowerBound
self.upperBound = upperBound
self.cost = cost
def displayArc(self):
print("Tail Node : ", self.tailNode, "\nHead Node : ", self.headNode, "\nLower Bound : ", self.lowerBound, "\nUpper Bound ; ", self.upperBound, "\nCost : ", self.cost, "\n")

class Node:
# Create an object of class node
def __init__(self, nodeName = 0, distLabel = 0, preNode = 0):
self.nodeName = nodeName
self.distLabel = distLabel
self.preNode = preNode

class Network:
# Creates a network from given arcs
def __init__(self, fileName):
global arcNo
arcNo = 0

self.fileName = fileName
f = open(self.fileName)
x = f.readlines()

arcList = [ Arc() for i in range(len(x))]

for i in range(len(x)):
temp = x[i]
temp = temp.split("\n")
temp = ",".join(map(str, temp))
temp = temp.split(",")
arcList[i] = Arc(temp[0], temp[1], temp[2], temp[3], temp[4])
arcNo += 1

print(arcNo)

net = Network("arcList.txt")
print(type(net))
print(net[1])

当打印语句出现时

4
<class '__main__.Network'>
Traceback (most recent call last):
File "Dijkstra.py", line 54, in <module>
print(net[1])
TypeError: 'Network' object does not support indexing

如何支持索引以便我可以通过索引调用网络对象?

最佳答案

假设 net[index] 返回 arcList 变量,你可以简单地覆盖你的 [] 运算符

class Network:
def __getitem__(self,index):
return arcList[index]

打印一个类也需要一个方法。这可能对你有帮助 How to print a class or objects of class using print()?

关于python - python中的对象索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38712056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com