首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中的对象索引

问python中的对象索引
EN

Stack Overflow用户
提问于 2016-08-02 12:58:26
回答 2查看 9.3K关注 0票数 2

我在python中创建了以下对象

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

代码语言:javascript
复制
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])

当print语句出现时,它说

代码语言:javascript
复制
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

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

EN

回答 2

Stack Overflow用户

发布于 2016-08-02 13:45:15

假设netindex返回arcList变量,您可以简单地覆盖[]运算符

代码语言:javascript
复制
class Network:
    def __getitem__(self,index):
         return arcList[index]

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

票数 3
EN

Stack Overflow用户

发布于 2016-08-02 13:03:28

为了支持索引,你的网络类应该有一个__getitem__()方法(http://docs.python.org/reference/datamodel.html#object.)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38712056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档