클래스 속성 vs 인스턴스 속성
클래스는 붕어빵을 만드는 틀
객체는 붕어빵 한 개
클래스 속성
- 클래스 내부의 속성
 
class Person:
    count = 0
person1 = Person("jhy")
print(Person.count)
print(Person.count)
# 0
# 0
Person.count = 100
print(Person.count)
print(person1.count)
# 100
# 100
- 위 코드에서 count가 클래스 속성
 
인스턴스 속성
- 객체화한 객체의 변수
 - 독립적인 변수
 - init 메서드를 통해 객체 생성시 만들어진 변수
 
class Person:
    count = 0
    
person1.count = 200
print(Person.count)
print(person1.count)
# 100
# 200
super()
- 부모클래스의 인스턴스 속성을 사용하기 위함
 - 부모클래스의 임시적인 객체를 반환하여 부모클래스의 변수를 사용할 수 있게 하는 것
 super().__init__()을 사용하여 부모 클래스의__init__()매직 메소드를 자식 클래스에 실행- 아래 코드 처럼 자식클래스에 
__init__메소드가 없으면super().__init__()없이도 부모클래스의 변수 사용 가능- IDE에서 자동 생성해주는것인가?
 
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def get_name(self):
        print(f'제 이름은 {self.name}입니다.')
    def get_age(self):
        print(f'제 나이는 {self.age}세 입니다.')
class Student(Person):
    # def __init__(self, name, age, GPA):
        # super().__init__(name, age)
        # self.GPA = GPA
    def get_GPA(self):
        print(f'제 학점은 {self.GPA}입니다.')
if __name__ == "__main__":
    student_a = Student('김OO', 27)
    student_a.get_name()  
# 제 이름은 김OO입니다.
- 하지만 자식클래스에 init 메소드가 있으면 에러 발생
 
class Person:
    count = 0
    def __init__(self):
        self.hi = 100
    def test(self):
        print("test function")
class Foo(Person):
    def __init__(self):
        print("Foo init")
    def func1(self):
        print("function 1")
    def func2(self):
        print("function 2")
if __name__ == "__main__":
    f = Foo()
    f.test()
    f.hi
# Parent Person class test function
# AttributeError: 'Foo' object has no attribute 'hi'
참고
[1] https://supermemi.tistory.com/177
[2] https://supermemi.tistory.com/176
          이 문서는
            jhy156456에 의해 작성되었습니다.
          
          마지막 수정 날짜:2023-01-25 19:53:00