我正在尝试使用我的Raspberry Pi创建一个python类来控制步进电机。它主要起作用,但每当我将列表定义为类变量时,我继续得到“'instancemethod'对象没有属性'__getitem__'
错误。错误消息列出这段代码作为罪魁祸首但是我不能如果seq [self.StepCounter] [pin]!= 0:它看起来有什么问题。如果我将它定义为实例变量或全局变量,它将起作用。
这是我的代码:
将RPi.GPIO导入为GPIO
进口时间
debug = True
class stepper:
clockwise = []
clockwise = range(0,4)
clockwise[0] = [1,0,0,0]
clockwise[1] = [0,1,0,0]
clockwise[2] = [0,0,1,0]
clockwise[3] = [0,0,0,1]
def __init__(self,pin1,pin2,pin3,pin4):
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
self.pin1 = pin1
self.pin2 = pin2
self.pin3 = pin3
self.pin4 = pin4
self.StepCounter = 0
self.pinarray = [pin1,pin2,pin3,pin4]
for pin in self.pinarray:
if debug == True:
print "Setup pin " + str(pin)
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin, False)
self.stepNum = 512.0
self.coilNum = 4.0
def setup(self,stepNum,coilNum):
self.stepNum = float(stepNum)
self.coilNum = float(coilNum)
self.partNum = self.coilNum * self.stepNum
def clockwise(self,speed):
seq = stepper.clockwise
self.WaitTime = (1.0 / (self.stepNum * self.coilNum)) * speed
for pin in range(0, 4):
xpin = self.pinarray[pin]
if seq[self.StepCounter][pin]!=0:
GPIO.output(xpin, True)
else:
GPIO.output(xpin, False)
self.StepCounter += 1
if (self.StepCounter==len(seq)):
self.StepCounter = 0
if (self.StepCounter<0):
self.StepCounter = len(seq)
time.sleep(self.WaitTime)
print "Adding Motor Instance"
motor = stepper(24,25,8,7)
print "Spinning Motor"
while "True":
motor.clockwise(5)
请有人告诉我它有什么问题并解释原因。谢谢
答案 0 :(得分:11)
你没有发布完整的追溯,但我可以猜一下:
def clockwise(self,speed):
seq = stepper.clockwise
self.WaitTime = (1.0 / (self.stepNum * self.coilNum)) * speed
for pin in range(0, 4):
xpin = self.pinarray[pin]
if seq[self.StepCounter][pin]!=0:
您将seq
设置为等于第一行上的方法stepper.clockwise
。然后几行后你尝试索引它:seq[self.StepCounter]
。但是获取方法的self.StepCounter
- 元素是什么意思?
没什么,因为:
'instancemethod' object has no attribute '__getitem__'
您不应将clockwise
用作列表名称和方法名称;只有最后执行的定义才会成立,所以当你到达seq = stepper.clockwise
时,它就是方法,而不是列表。