ABOUT ME

IT와 컴퓨터 관련 팁, 파이썬 등과 아파트 정보, 일상적인 경험 등의 생활 정보를 정리해서 올리는 개인 블로그

  • [python] 파이썬 클래스와 객체의 본질, 그리고 독특한 특성
    코딩 연습/코딩배우기 2020. 9. 9. 15:33
    반응형

     

    ■ 객체 변수의 선언과 초기화

    #  아래 클래스에서 메서드 정의만 보이고 변수 선언은 없지만, 파이썬은 객체에 필요한 변수 i를 알아서 생성해준다.  i변수가 생성되는 시점은 객체 내에서 해당 변수를 대상으로 대입연산을 처음 진행하는 순간임

    class Simple1:
        def set_i(self, i):
            self.i = i
        
        def get_i(self):
            return self.i
    
    s1 = Simple1()
    s1.set_i(200)  # 객체 내 변수 i 생성, 200 대입(할당)
    print(s1.get_i()) # 200
    
    s12 = Simple1()
    #s12.get_i()  # 객체 내 i 변수 미생성 단계에서 호출하면 오류 발생
    # AttributeError: 'Simple' object has no attribute 'i'

     

    # 클래스 정의할 때, 객체 생성 시 자동으로 호출되는 __init__ 메서드 정의로 객체 내 필요한 모든 변수를 초기화한다.

    class Simple2:
        def __init__(self):
            self.i = 0
            
        def set_i(self, i):
            self.i = i
        
        def get_i(self):
            return self.i
        
    s2 = Simple2()  # 객체 생성과 변수 초기화 완료
    print(s2.get_i()) # 0
    

    good4me.co.kr

     

     파이썬 클래스와 객체의 독특한 특성

    # 객체 생성 후 변수와 메서드 추가하는 특성

    class Simple3:
        def get_i(self):
            return self.i
    
    s3 = Simple3()
    s3.i = 20  # 생성된 객체에 변수 i 추가, 값 20 대입
    print(s3.get_i())  # 20
    
    s3.hello = lambda : print('hi~~')  # 생성된 객체에 hello() 메서드 추가
    print(s3.hello())
    
    

     

    # 클래스에 변수 추가하기

    class Simple4:
        def __init__(self, i):
            self.i = i
            
        def get_i(self):
            return self.i
    
    Simple4.n = 7  # 클래스 변수 n 추가, 초기화
    # 클래스에 직접 클래스 변수를 만들 수 있다.
    
    s4 = Simple4(5)
    print(s4.i)  # 5
    print(s4.get_i())  # 5
    
    print(Simple4.n)  # 7
    print(s4.n)  # 7
    # 객체에 찾는 변수가 없으면 클래스에서 그 변수를 찾는다.
    

     

    # 자료형 확인 시 사용하는 type의 정체

    print(type(type))  # <class 'type'>  - 클래스임
    
    print(type([1, 2]))  # <class 'list'> - [1, 2]는 list 클래스의 객체
    print(type(list))  # <class 'type'>  - list는 type 클래스의 객체
    print(type(tuple))  # <class 'type'>
    print(type(str))  # <class 'type'>
    print(type(int))  # <class 'type'>
    print(type(bool))  # <class 'type'>
    
    print(type(Simple4))  # <class 'type'>
    # Simple4 클래스도 type 클래스의 객체임
    
    

    #### 클래스는 type이라는 클래스의 객체이다.
    #### 고로, 객체를 대상으로 할 수 있는 것 대부분을 클래스를 대상으로도 할 수 있다.

    # 클래스가 객체이기 때문에 변수에 클래스를 담을 수 있다.
    
    Simple4.x = 10
    Simple4.y = 20  
    
    simple = Simple4
    ss1 = simple(10)
    ss2 = simple(20)
    
    print(ss1.get_i(), ss1.n, ss1.x, ss1.y)  # 10 7 10 20
    print(ss2.get_i(), ss2.n, ss1.x, ss1.y)  # 10 7 10 20
    

     

    참고자료 : 윤성우의 열혈파이썬 중급편

     

     

    반응형
Designed by goodthings4me.