从列表中的对象访问方法

时间:2013-12-03 18:07:52

标签: python list

我是Python的新手(来自C ++)所以我仍然习惯了一些事情。

我创建了一个名为Sensor的类,我将其用作传感器,用于检测化身或玩家何时进入其中。我希望一次最多有20个传感器,所以我想将它们存储在一个列表中然后遍历列表,检查每个传感器是否有检测到的条目。

我有以下代码:

class Sensor:

    def __init__(self, loc, size=1, enabled=True):
        self.enabled = enabled
        self.distOfBorderFrmCentre = size / 2.0
        self.location = loc

    # Additional Sensor code here. Just not implemented yet so would not
    # benefit the post.

    def position(self):
        # No real use. Using this function for demo reasons
        return self.position

self.sensors = [ Sensor(loc) for loc in self.route ]
for i in range(len(self.sensors)):
    print self.sensors[i].position()

# Also gives same output
#for sensor in self.sensors:
    #print sensor .position()

我得到的输出是:

<bound method Sensor.position of <sensor.Sensor instance at 0x03628E40>>
<bound method Sensor.position of <sensor.Sensor instance at 0x03628DC8>>
<bound method Sensor.position of <sensor.Sensor instance at 0x03628DF0>>
<bound method Sensor.position of <sensor.Sensor instance at 0x03628E18>>
<bound method Sensor.position of <sensor.Sensor instance at 0x03628E40>>

所以我错过了什么?我怀疑我可能是。我搜索并搜索过,但每次看到列表中对象调用方法的示例时,我上面列出的语法都是使用的。

由于

2 个答案:

答案 0 :(得分:2)

您需要调用方法:

for i in range(len(self.sensors)):
    print self.sensors[i].position()

请注意尾随的括号。


我已经改变了一些你的例子,使它可以运行。这个片段有效:

#! /usr/bin/python2.7

class Sensor:

    def __init__(self, loc, size=1, enabled=True):
        self.enabled = enabled
        self.distOfBorderFrmCentre = size / 2.0
        self.location = loc


    def position(self):
        return self.location

sensors = [ Sensor(loc) for loc in ('Loc 1', 'Loc 2', 'Loc 3') ]
for i in range(len(sensors)):
    print sensors[i].position()

#Previous two lines are a bit senseless, you can use:
for sensor in sensors:
    print sensor.position()

答案 1 :(得分:1)

当你有:

for i in range(len(self.sensors)):
    print self.sensors[i].position

您正在打印对该类的position方法的引用,但现在您已将其更改为:

for i in range(len(self.sensors)):
    print self.sensors[i].position()

你现在每次调用这个函数,这很棒,除了函数的返回值:

def position(self):
    # No real use. Using this function for demo reasons
    return self.position

是否返回对函数本身的引用...这实际上是你第一次做的事情的循环方法...让你的position函数做更有意义的事情......(也许:return self.location或其他用于测试的内容)

相关问题