본문 바로가기
Programming/Python

[클래스] 기반 클래스의 속성 사용하기

by 용스토리랜드 2023. 3. 13.

기반 클래스에 있는 인스턴스 속성을 사용하기. 

class Person : 
  def __init__(self) :
    print("Person __init__")
    self.hello = '안녕하세요.'
    
class Student(Person) : 
  def __init__(self) :
    print("Student __init__")
    self.school = "코딩도장"
    
james = Student()
print(james.school) 
print(james.hello) # 기반 클래스의 속성을 출력하려고 하면 에러가 발생한다.
# 실행결과

Student __init__
파이썬 코딩 도장
Traceback (most recent call last):
  File "C:\project\class_inheritance_attribute_error.py", line 14, in <module>
    print(james.hello)
AttributeError: 'Student' object has no attribute 'hello'

실행을 해보면 에러가 발생. 왜냐하면 기반 클래스 Person 의 __init__ 메서드가 호출되지 않았기 때문이다. 실행 결과만 잘 보면 'Student __init__' 만 출력되었다. 

 

즉, Person 의 __init__ 메서드가 호출되지 않으면 self.hello = '안녕하세요.' 도 실행되지 않아서 속성이 만들어지지 않는다. 

 

# super() 로 기반클래스 초기화하기

이때는 super() 를 사용해서 기반 클래스의 __init__ 메서드를 호출해준다. 다음과 같이 super() 뒤에 .(점) 을 붙여서 메서드를 호출하는 방식이다. 

 

super()로 기반 클래스(부모 클래스)를 초기화해줌으로써, 기반 클래스의 속성을 subclass가 받아오도록 한다. (초기화를 하지 않으면, 부모 클래스의 속성을 사용할 수 없음)

 

  • super().메서드()
class Person : 
  def __init__(self) : 
    print("Person __init__") # 호출됨
    self.hello = "안녕하세요"

class Student(Person) : 
  def __init__(self) : 
    print("Student __init__)
    super().__init__() # super() 로 기반 클래스의 __init__메서드 호출
    self.school = "코딩 도장"
    
james = Student() 
print(james.school) 
print(james.hello)

>>> Student __init__
>>> Person __init__
>>> 파이썬 코딩 도장 
>>> 안녕하세요.

# 기반 클래스를 초기화하지 않아도 되는 경우 

만약 파생 클래스에서 __init__ 메서드를 생략한다면 기반 클래스의 __init__ 이 자동으로 호출되므로 super() 는 사용하지 않아도 됩니다.

class Person : 
  def __init__(self) :
    print("Person __init__")
    self.hello = "안녕하세요."
    
class Student(Person) :
  pass 
  
james = Student()
print(james.hello)

>>> Person __init__
>>> 안녕하세요.

이처럼 파생클래스에 __init__ 메서드가 없다면 기반 클래스의 __init__ 이 자동으로 호출되므로 기반 클래스의 속성을 사용할 수 있다.

 

참고 | 좀 더 명확하게 super 사용하기 

super 는 다음과 같이 subclass 와 self 를 넣어서 현재 클래스가 어떤 클래스인지 명확하게 표시하는 방법도 있습니다. super() 와 기능은 같습니다.

 

super( subclass, self).method

 

class Student(PErson) : 
  def __init__(self) : 
    print("Student __init__")
    super(Student, self).__init__() # super(subclass, self) 로 기반 클래스의 메서드 호출
    self.school = '파이썬 코딩 도장'

 

반응형