클래스 메소드에 self를 적고 안적고는 무슨 차이인가요?
조회수 8787회
발생하는 문제 및 실행환경
파이참에서 코드를 짜니까 자동으로 self
를 붙여주던데
이건 왜 해주는건가요?
self
가 무슨 역할을 하길래 self
를 빼면 에러가 나는 건지 궁금합니다.
소스코드
class Test(object):
def method_one(self):
print "Called method_one"
def method_two(): #여기서 빨간 줄이 뜸...
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two() ##안됨
1 답변
-
self를 붙인 쪽을 bound, 안 붙인 쪽은 unbound 메소드라 합니다.
보통 멤버 함수를 호출하는 경우, bound 함수인
method_one()
은 호출하면a_test.method_one()
은
Test.method_one(a_test)
로 변환됩니다. 그래서 unbound 함수의 경우는
TypeError
가 발생하지요.에러내용
>>> a_test = Test() >>> a_test.method_two() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method_two() takes no arguments (1 given)
저기서
method_two() takes no arguments (1 given)
를 보시면 알겠지만self
가a_test
를 받아주는 역할로 있어야 하는데self
가 없기 때문에 인자가 너무 많이 들어왔다는 겁니다.self
를 쓰기 싫으면 데코레이터를 써서 "이 메소드method_two
는 bound method를 만들지 마라"고 설정할 수 있습니다.class Test(object): def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method two" #에러 사라짐
댓글 입력