Python Object Oriented Programming
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
?
i()
doesn't work?
Why does self.i()
work?
Why is i
an int
(hen开发者_开发技巧ce the 'int' object is not callable TypeError
)?
That's a lot of questions. Thanks in advanceYou're overwriting i
within loop. When you're "preceding" i
with self
, you're creating different variable, which is not overwritten.
@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()
精彩评论