Python

[점프 투 파이썬] 생성자(Constructor)와 클래스의 상속, 메서드 오버라이딩(Method Overriding), 클래스 변수

kyra 2022. 7. 31. 19:37
생성자(Constructor)

객체에 초깃값을 설정해야 할 때

  • 객체에 초깃값을 설정하고자 할 때 __init__을 사용하면 이 메서드는 생성자가 된다.

 

class FourCal:
#생성자 __init__메서드를 입력
    def __init__(self, first, second):
        self.first = first
        self.second = second
        
    def setdata(self, first, second): 
        self.first = first
        self.second = second
 

 

 

클래스의 상속

어떤 클래스를 만들 때 다른 클래스의 기능을 사용할 수 있게 물려 받는 것

 

  • 상속하는 이유

기존 클래스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하려고 할 때 사용

 

  • 상속 방법

class 클래스 이름 (상속할 클래스 이름)

 

<FourCal 클래스를 상속받는 MoreFourCal 클래스 만들기>

class MoreFourCal(FourCal):
    pass

a = MoreFourCal(3, 4)
print(a.add())
 
  • __init__ 도 이미 상속 받은 FourCal 클래스에 있으므로 MoreFourCal에는 추가하지 않아도 된다.
class MoreFourCal(FourCal):
    def pow(self):
        result = self.first ** self.second
        return result
    

a = MoreFourCal(3, 4)
print(a.pow())
 

 

 

메서드 오버라이딩 (Method Overriding)

메서드를 변형하고자 할 때

<0으로 나누면 값이 0으로 나오도록 div메서드 기능 추가>

#기존의 FourCal 클래스 속 div 메서드  
  def div(self):
        result = self.first/self.second
        return result

#메서드 오버라이딩
class SafeFourCal(FourCal):  -> 상속받는 것처럼 새로운 클래스 생성
    def div(self):           -> 원래 클래스에 있던 메서드에 새로운 기능 추가
        if self.second = 0 :
            return 0
        else:
            return self.first / self.second
 

 

클래스 변수
  • 사용법

클래스 이름. 클래스 변수

 

- 클래스의 변수를 바꿀 경우 클래스로 생성된 객체에 모두 공유된다.

>>> a = Family()
>>> b = Family()
>>> print(a.lastname)
김
>>> print(b.lastname)
김

>>> Family.lastname = "박"
>>> print(a.lastname)
박
>>> print(b.lastname)
박