首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python面向对象编程

Python面向对象编程
EN

Stack Overflow用户
提问于 2011-01-19 23:28:01
回答 2查看 1.7K关注 0票数 2

我试图用python来理解面向对象的编程。我是编程新手。我的这个类给了我一个我不理解的错误,如果有人能为我提供更多的帮助,我会很高兴的:

代码语言:javascript
运行
复制
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),它就可以工作。

代码语言:javascript
运行
复制
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()可以工作?

为什么iint (因此是'int' object is not callable TypeError)?

这是很多问题。提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-19 23:29:52

你在循环中重写了i。当您使用self“先于”i时,您创建的是不同的变量,该变量不会被覆盖。

票数 9
EN

Stack Overflow用户

发布于 2011-01-19 23:33:19

@SilentGhost的答案是对的。

为了说明这一点,尝试将test_two方法更改为:

代码语言:javascript
运行
复制
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(设置为方法)(请参阅注释)

代码语言:javascript
运行
复制
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这样的变量。相反,您可以只调用该方法来替换

代码语言:javascript
运行
复制
i()

使用

代码语言:javascript
运行
复制
self.test_one()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4737088

复制
相关文章

相似问题

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