2012-03-01 3 views
0

클래스와 두 가지 방법이 있습니다. 하나의 메소드는 사용자로부터 입력을 받고 x와 y의 두 변수에 저장합니다. 입력을 받아들이는 다른 메소드가 x와 y에 그 입력을 추가하기를 원합니다. 어떤 숫자 z에 대해 calculate (z)를 실행하면, 전역 변수 x와 y가 정의되지 않았다는 에러가 발생합니다. 분명히 이것은 calculate 메소드가 getinput()에서 x와 y에 접근하지 못한다는 것을 의미합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?파이썬에서 메소드간에 변수를 넘겨 줍니까?

class simpleclass (object): 
    def getinput (self): 
      x = input("input value for x: ") 
      y = input("input value for y: ") 
    def calculate (self, z): 
      print x+y+z 
+1

'raw_input'을 사용하십시오 –

+0

@yi_H :'raw_input()'이'input()'보다 선호되는 이유를 설명해 주시겠습니까? –

답변

2

당신은 self.xself.y을 사용하고 싶습니다. 그래서 같이 :

class simpleclass (object): 
    def getinput (self): 
      self.x = input("input value for x: ") 
      self.y = input("input value for y: ") 
    def calculate (self, z): 
      print self.x+self.y+z 
+0

@DSM : D' oh! 좋은 캐치. 수정할 수정. –

1

내부 클래스라는 변수가있다 self 당신은 사용할 수 있습니다

class Example(object): 
    def getinput(self): 
     self.x = input("input value for x: ") 
    def calculate(self, z): 
     print self.x + z 
10

는이 인스턴스 변수를 할 필요가 :

class simpleclass(object): 
    def __init__(self): 
     self.x = None 
     self.y = None 

    def getinput (self): 
     self.x = input("input value for x: ") 
     self.y = input("input value for y: ") 

    def calculate (self, z): 
     print self.x+self.y+z 
+1

+1은 __init __() 메소드의 사용법을 보여주는 대부분의 정답입니다. –

1

xy 지역 변수입니다. 당신이 그 기능의 범위를 벗어날 때 그들은 파괴됩니다.

class simpleclass (object): 
    def getinput (self): 
      self.x = raw_input("input value for x: ") 
      self.y = raw_input("input value for y: ") 
    def calculate (self, z): 
      print int(self.x)+int(self.y)+z 
+0

아마도 raw_input으로 전환 할 때 어떤 시점에서 문자열에서 숫자를 얻고 싶을 것입니다. – DSM

+0

@DSM : 맞습니다. 고마워 –

0
class myClass(object): 

    def __init__(self): 

    def helper(self, jsonInputFile): 
     values = jsonInputFile['values'] 
     ip = values['ip'] 
     username = values['user'] 
     password = values['password'] 
     return values, ip, username, password 

    def checkHostname(self, jsonInputFile): 
     values, ip, username, password = self.helper 
     print values 
     print '---------' 
     print ip 
     print username 
     print password 

init 메소드의 클래스를 초기화한다. 도우미 함수는 일부 변수/데이터/특성을 보유하고이를 호출 할 때 다른 메서드로 해제합니다. 여기 jsonInputFile은 json입니다. checkHostname은 일부 장치/서버에 로그인하고 호스트 이름을 확인하기 위해 작성된 메소드이지만 IP 주소, 사용자 이름 및 암호가 필요하며 이는 도우미 메서드를 호출하여 제공됩니다.

관련 문제