Python 面向对象编程

2 投票
2 回答
1788 浏览
提问于 2025-04-16 10:15

我正在尝试理解用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)?
这些问题有点多,提前谢谢大家!

2 个回答

2

@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()
9

你在循环里把 i 的值给覆盖掉了。当你在 i 前面加上 self 的时候,其实是在创建一个不同的变量,这个变量不会被覆盖。

撰写回答