2011-01-19 36 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')iにtest_one機能を割り当てることはありませんか?
どうしてi()はうまくいかないのですか?
self.i()はなぜ機能しますか?
なぜiint(したがって'int' object is not callable TypeError)ですか?
これはたくさんの質問です。事前に感謝します

+0

i() 

を交換するメソッドを呼び出すことができます。私はxrange()を反復するためにそれを使用しているので、私は '私'を使ってはいけません。 pheeew – kassold

答えて

9

ループの中でiを上書きしています。 の前に「self」と「先行する」ときは、上書きされない別の変数を作成しています。

+0

ペイ、はい。ありがとう – kassold

2

@SilentGhostは、彼の答えでお金の上に右です。説明するために

、これにtest_two方法をchaningてみてください。

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メソッドを割り当てる必要はありません。代わりに、あなただけの私はちょうどそれを実現考える

self.test_one() 
+0

はい、はい、はい。ありがとう – kassold

関連する問題