2

Am trying to understand object oriented programming with python. Am new to programming. I have this class that is giving me an error I don't understand and I will be glad if anyone can throw more light on this for me:

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')

If I run this class I get 'int' object is not callable" TypeError

However, if I precede the i with self (self.i), it works.

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

My question is, doesn't i = getattr(self, 'test_one') assign the test_one function to i?
How come i() doesn't work?
Why does self.i() work?
Why is i an int (hence the 'int' object is not callable TypeError)?
That's a lot of questions. Thanks in advance

1
  • i think i just realised it. I shouldn't have used 'i' since am using it to iterate over xrange(). pheeew Commented Jan 19, 2011 at 15:30

2 Answers 2

9

You're overwriting i within loop. When you're "preceding" i with self, you're creating different variable, which is not overwritten.

Sign up to request clarification or add additional context in comments.

Comments

2

@SilentGhost is right on the money with his answer.

To illustrate, try chaning the test_two method to this:

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

Your code overwrite the variable i (set as a method) within the for loop (see comments)

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

In addition, you certainly don't need to assign the test_one method to a variable like i. Instead, you can just call the method replacing

i()

with

self.test_one()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.