2011-01-19 143 views
2

我試圖用python理解面向對象的編程。編程新手。 我有這個類,它是給我的錯誤,我不明白,我會很高興,如果任何人都可以投入更多的光這對我來說: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之前加上selfself.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()有效?
爲什麼iint(因此'int' object is not callable TypeError)?
這是很多問題。在此先感謝

+0

我想我只是意識到這點。我不應該使用'i',因爲我正在使用它來遍歷xrange()。 pheeew – kassold 2011-01-19 15:30:13

回答

9

您正在覆蓋循環內的i。當您在「i」之前「self」時,您正在創建不會被覆蓋的其他變量。

+0

pheeeew,是的。謝謝 – kassold 2011-01-19 15:55:17

2

@SilentGhost對他的答案是正確的。

爲了說明,嘗試chaning的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() 

您的代碼覆蓋內的變量i(設定爲方法)for循環(見註釋)

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

是的,是的,是的。謝謝 – kassold 2011-01-19 15:54:03