이번 포스트에서는 파이썬의 클래스에 대하여 정리하려고 한다.
파이썬은 객체지향언어로 객체와 객체 간의 상호작용이 매우 중요하다고 생각한다. 각 객체는 각자만의 고유한 기능 및 성격을 가진다. 객체의 고유한 기능과 성격은 클래스에 의하여 정의되며, 그 클래스로 만든 객체 생성을 우리는 인스턴스를 생성 한다고한다.
객체 = 클래스()
위는 인스턴스를 생성하는 일반적인 방법이다.
더욱 구체적인 예시를 들기 위해 Student이라는 클래스를 만들어보자
class Student:
#생성자
def __init__(self, name, age, mathScore, engScore):
self.name = name
self.age = age
self.mathScore = mathScore
self.engScore = engScore
# 메서드
def setdata(self, name, age, mathScore, engScore):
self.name = name
self.age = age
self.mathScore = mathScore
self.engScore = engScore
def showInfo(self): # 학생 정보
print("학생의 이름은 %s이고, 나이는 %d입니다." % (self.name, self.age))
def sum(self): # 점수 합계
result = self.mathScore + self.engScore
print("점수의 합은 %d입니다." %result)
def mathGrade(self): # 수학 점수 등급
if self.mathScore >= 90:
print("A학점입니다.")
elif self.mathScore >= 80:
print("B학점입니다.")
elif self.mathScore >= 70:
print("C학점입니다.")
elif self.mathScore >= 60:
print("D학점입니다.")
else:
print("F학점입니다.")
def engGrade(self): # 영어 점수 등급
if self.engScore >= 90:
print("A학점입니다.")
elif self.engScore >= 80:
print("B학점입니다.")
elif self.engScore >= 70:
print("C학점입니다.")
elif self.engScore >= 60:
print("D학점입니다.")
else:
print("F학점입니다.")
Student 클래스는 학생의 이름과 나이 수학, 영어 점수를 바탕으로 다양한 메서드를 구현하였다.
참고로 Python에서 self는 Java의 this와 비슷한 기능을 한다. 객체 생성시 객체 자체가 self에 전달 된다.
이 클래스를 바탕으로 studentLee라는 객체를 생성해보자
Python에서 객체 생성시 클래스 형태는 다음과 같다.
객체 = 모듈명.클래스명()
모듈의 클래스에 접근하기 위하여 클래스명 앞에 "모듈."을 입력 해준다.
아래는 Student 클래스를 사용하여 객체를 생성하였다.
import Student
studentLee = Student.Student("Lee", 24, 76, 85)
studentLee.showInfo()
studentLee.sum()
studentLee.mathGrade()
studentLee.engGrade()
import를 이용하여 외부 모듈에 접근이 가능하다.
생성자에 의해 객체 생성과 동시에 매개변수를 통해서 객체 변수에 값이 전달 된다. 또한 객체는 Student 클래스의 인스턴스 이므로 Student 클래스의 다양한 메서드를 활용 가능하다.
다음은 위의 Student 클래스의 상속을 활용한 ModStudent 클래스이다.
class ModStudent(Student): # 클래스 상속
def average(self): # 점수 평균 메서드 추가
result = (self.mathScore + self.engScore) / 2
print("점수의 평균은 %d입니다." % result)
def mathGrade(self): # 메서드 오버라이딩
if self.mathScore >= 95:
print("A학점입니다.")
elif self.mathScore >= 85:
print("B학점입니다.")
elif self.mathScore >= 75:
print("C학점입니다.")
elif self.mathScore >= 65:
print("D학점입니다.")
else:
print("F학점입니다.")
ModStudent 클래스는 학생의 수학 점수와 영어 점수의 평균을 구할 수 있는 메서드를 추가하였다. 또한 ModStudent 클래스는 수학 등급 산출에서 기준 점수를 5점씩 올려 주기 위하여 메서드 이름은 그대로 둔 채 메서드 오버라이딩을 사용하였다.
상속을 이용하여 생성한 ModStudent 클래스를 이용하여 새로운 객체를 생성해 보자
import Student
studentKim = Student.ModStudent("Kim", 25, 84, 70)
studentKim.showInfo()
studentKim.sum()
studentKim.average()
studentKim.mathGrade()
studentKim.engGrade()
ModStudent 클래스를 이용하여 studentKim 객체를 생성 하였다.
ModStudent 클래스는 Student 클래스의 상속을 받아 Student 클래스의 메서드는 물론 새로 추가한 메서드까지 사용이 가능하다.