ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python Class - 2
    Programming/python 2021. 6. 24. 22:17
    728x90

    클래스 변수 와 인스턴스 변수

     

    Swift에도 존재하지만, 

    클래스 변수 : 클래스 전체에서 공유하는 변수

    인스턴스 변수 : 생성된 객체 안에서만 공유되는 변수

     

    # 클래스 변수와 인스턴스 변수
    # 클래스 변수는 모든 클래스에서 공유, 인스턴스 변수는 생성후 사용 가능
    
    class Student():
        # 클래스 변수
        student_count = 0
    
        def __init__(self, name, number):
            # 인스턴스 변수
            self._name = name
            self._number = number
            Student.student_count += 1
    
        def __str__(self):
            return 'str {}'.format(self._name)
        def __repr__(self):
            return 'repr {}'.format(self._name)
        def detail_info(self):
            print('current id = {}'.format(id(self)))
            print('Student detail info : {} {}'.format(self._name, self._number))
        def __del__(self):
            Student.student_count -= 1
    
    student1 = Student('Choi', 1)
    student2 = Student('Kwon', 2)
    
    print(id(student1), id(student2))
    # 2292282828112 2292284690640
    
    print(student1 == student2)
    # False, ID값 비교이기때문에 False
    
    print(student1 is student2)
    # True, 같은 Student class의 객체이기때문에..

     

    'Programming > python' 카테고리의 다른 글

    Python Class - 4  (0) 2021.06.29
    Python Class - 3  (0) 2021.06.24
    Python Class - 1  (0) 2021.06.24
    다익스트라(Dijkstra) 알고리즘  (0) 2021.03.10
    Bisect Module  (0) 2021.03.09
Designed by Tistory.