我试图用python来理解面向对象的编程。我是编程新手。我的这个类给了我一个我不理解的错误,如果有人能为我提供更多的帮助,我会很高兴的:
class TimeIt(object):
def __init__(self, name):
self.name = name
def test_one(self):
print 'executed'
def test_two(self, word):
self.word = word
i = getattr(self, 'test_one')
for i in xrange(12):
sleep(1)
print 'hello, %s and %s:' % (self.word, self.name),
i()
j = TimeIt('john')
j.test_two('mike')如果我运行这个类,我会得到'int' object is not callable" TypeError
但是,如果我在i前面加上self (self.i),它就可以工作。
class TimeIt(object):
def __init__(self, name):
self.name = name
def test_one(self):
print 'executed'
def test_two(self, word):
self.word = word
self.i = getattr(self, 'test_one')
for i in xrange(12):
sleep(1)
print 'hello, %s and %s:' % (self.word, self.name),
self.i()我的问题是,i = getattr(self, 'test_one')不是将test_one函数赋值给i吗
为什么i()不能工作?
为什么self.i()可以工作?
为什么i是int (因此是'int' object is not callable TypeError)?
这是很多问题。提前感谢
发布于 2011-01-19 23:29:52
你在循环中重写了i。当您使用self“先于”i时,您创建的是不同的变量,该变量不会被覆盖。
发布于 2011-01-19 23:33:19
@SilentGhost的答案是对的。
为了说明这一点,尝试将test_two方法更改为:
def test_two(self, word):
self.word = word
i = getattr(self, 'test_one')
for some_other_variable_besides_i in xrange(12):
sleep(1)
print 'hello, %s and %s:' % (self.word, self.name),
i()您的代码覆盖了for循环中的变量i(设置为方法)(请参阅注释)
def test_two(self, word):
self.word = word
i = getattr(self, 'test_one')
# i is now pointing to the method self.test_one
for i in xrange(12):
# now i is an int based on it being the variable name chosen for the loop on xrange
sleep(1)
print 'hello, %s and %s:' % (self.word, self.name),
i()此外,您当然不需要将test_one方法赋给像i这样的变量。相反,您可以只调用该方法来替换
i()使用
self.test_one()https://stackoverflow.com/questions/4737088
复制相似问题