2014-12-04 5 views
-6

클래스에 문자열을 사용할 수 있습니까? 변수 문자열이 문자열이기 때문에 내가 이것을 실행하면클래스에 문자열을 사용할 수 있습니까

class test: 
    def __init__(self,string,integer): 
     string = self.string 
     integer = self.integer 

string = 'hi' 
integer = 4 
variable = test(string, integer) 

나는 오류가 발생 : 내 컴퓨터 과학 프로젝트에 대한 내가 내 객체의 문자열을 사용합니다,하지만 난 여기에 단순 들어 에 드릴 수 없습니다은 예입니다 그것이 무엇 못하고으로의,

class test: 
    def __init__(self,string,integer): 
     self.string = string 
     self.integer = integer 

string = 'hi' 
integer = 4 
variable = test(string, integer) 
+0

전체 오류보기; 질문을 수정할 때 들여 쓰기를 처리하십시오. – Evert

+0

질문에 대한 답은 yes입니다. – Evert

+0

'integer = self.integer' 무엇을 기대합니까? (self.integer가 정의 된 적이 없기 때문에 특히 그렇습니까?) – njzk2

답변

2

문자열을 사용하는 방법 당신은 거꾸로있어이된다 "자기를." 방법. 원하는 내용은 다음과 같습니다.

class Test(object): 
    def __init__(self, string, integer): 
     # here 'string' is the parameter variable, 
     # 'self' is the current Test instance. 
     # ATM 'self' doesn't yet have a 'self.string' 
     # attribute so we create it by assigning 'string' 
     # to 'self.string'. 
     self.string = string 
     # and from now on we can refer to this Test instance's 
     # 'string' attribute as 'self.string' from within Test methods 
     # and as 'varname.string' from the outside world. 

     # same thing here... 
     self.integer = integer 

var = Test("foo", 42) 
1

귀하의 문제는 문자열되지 않습니다 : 내 질문은, 클래스

1

나는 방금 __init__ 부분을 섞어 놓았습니다. 그것은해야한다 :

self.string = string 

하지 :

string = self.string 
관련 문제