클래스 생성
- 클래스 이름 짓기
- 대문자로 시작
- 단어와 단어 사이 연결은 대문자
__init__(self)
- 클래스 내 사용 변수 설정
self
: 해당 클래스에서 사용되는 로컬변수 설정
class FourCalculation:
"""A class for four aritthmetic calculation"""
# __init__으로 시작: 클래스 내 사용 변수 설정
# self: 해당 클래스에서 사용되는 로컬변수 역할 지정
def __init__(self, first, second):
self.first = first
self.second = second
if second == 0:
raise ValueError('the number must NOT be zero')
def add(self):
return self.first + self.second
def mul(self):
return self.first * self.second
def sub(self):
return self.first - self.second
def div(self):
return self.first / self.second
%save fourcalculation.py
클래스 사용
.py
파일 불러와 클래스 임포트b
라는 객체에 클래스 정보 입력- 메서드 활용하여 계산
from fourcalculation import FourCalculation
# import fourcalculation as fc
b = FourCalculation(19, 8)
# b = fc.FourCalculation(19, 8)
print(b.add(), b.mul(), b.sub(), b.div())
클래스 상속
SuperClass와 SubClass
- SuperClass: 부모 클래스
- SubClass: 자식 클래스로, 상위 클래스를 상속 받아서 해당 클래스 내 변수와 메서드 사용가능
- 확장 및 구체화할 떄 사용
- 객체 지향 코딩에 유용함
-
부모 클래스(super class)를 상속 받아서 해당 클래스 변수 및 메서드 모두 상속
-
단, 변경가능 > overriding
-
class ClassName(SuperClass)
-
super().__init__(first, second)
슈퍼클래스에 변수 활용- 단, third는 새롭게 설정
-
메서드 변경
from fourcalculation import FourCalculation
class FiveCalculation(FourCalculation):
"""Adding power calculation"""
def __init__(self, first, second, third):
super().__init__(first, second)
self.third = third
def pow(self):
return self.first ** self.second + self.third
def div(self): # Method overriding
if self.second == 0:
return 0
else:
return self.first/self.second
c = FiveCalculation(4, 2, 3)
print(c.pow(), c.add(), c.sub())
예시
- Employee 클래스에
GetEmployee()
메스드 내 사용되는Name()
메서드 - 상위 클래스를 상속받았기 때문에 사용가능
# SuperClass
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
# SubClass
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self, first, last)
self.staffnumber = staffnum
def GetEmployee(self):
return self.Name() + "," + self.staffnumber
x = Person('haejun', 'hyun')
x.Name()
y = Employee('haejun', 'hyun','1234')
x.GetEmployee()