python

클래스 메소드에 인수로 self 주는 이유

장곰부대 2018. 4. 28. 23:45

self가 반드시 필요한 것은 아니다


self를 안 쓰고 쓰는 차이는

클래스 변수, 메소드인스턴스의 변수, 메소드중 뭘 만드는 가이다.


class WhySelf:

    class_variable = 1

    def __init__(self):
        self.instance_variable = 2
    
    def instance_func(self):
        print('instance_func')
    
    def class_func():
        print('class_func')

//클래스 함수, 변수 사용
WhySelf.class_func()
print(WhySelf.class_variable)

//인스턴스 함수, 변수 사용
x = WhySelf()

x.instance_func()
WhySelf.instance_func(x)
#x.class_func()
print(x.class_variable)
print(x.instance_variable)


약간 방향이 다르지만

비슷한 주제에 관한 

파이썬 제작자 답변도 읽을 만 하다.

http://neopythonic.blogspot.kr/2008/10/why-explicit-self-has-to-stay.html