2011-01-19 6 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

를 얻을 수

그러나 내가 (self.i)으로 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()를 반복하는 데 사용하기 때문에 'i'를 사용해서는 안됩니다. pheeew – kassold

답변

9

루프 내에서 i을 덮어 쓰는 중입니다. 의 앞에 ""을 붙이면 덮어 쓰지 않는 다른 변수가 생성됩니다.

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

에서 (주석 참조) 게다가, 당신은 확실히 i과 같은 변수에 test_one 메소드를 할당 할 필요가 없습니다. 대신, 당신은 단지 난 그냥 그것을 실현 생각

self.test_one() 
+0

예, 예, 예. 감사 – kassold