2023. 8. 9. 11:31
파이썬
728x90
반응형
여기서는 날짜에 관해서 편리한 기능을 제공하는 표준 파이썬 라이브러리 모듈 datetime을 사용하고 있다.
# Person 클래스
import datetime
class Person(object):
def __init__(self, name):
self.name = name
try:
lastBlank = name.rindex(' ')
self.lastName = name[lastBlank+1:]
except:
self.lastName = name
self.birthday = None
def getName(self):
return self.name
def getLastName(self):
return self.lastName
def setBirthday(self, birthdate):
self.birthday = birthdate
def getAge(self):
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
def __It__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def __str__(self):
return self.name
다음 코드는 Person 클래스를 사용하고 있다.
me = Person('Joy Kit')
him = Person('Jae Sung')
her = Person('Jyung Un Hyang')
print('His last name is ', him.getLastName())
print('My name is ', me.getName())
me.setBirthday(datetime.date(2023, 5, 25))
him.setBirthday(datetime.date(1958, 8, 27))
her.setBirthday(datetime.date(1991, 2, 19))
print(me.getName(), 'is', me.getAge(), 'days old')
print(him.getName(), 'is', him.getAge(), 'days old')
print(her.getName(), 'is', her.getAge(), 'days old')
출력 결과
His last name is Sung
My name is Joy Kit
Joy Kit is 74 days old
Jae Sung is 23721 days old
Jyung Un Hyang is 11857 days old
앞의 코드에서 Person의 인스턴스가 생길 때마다 __init__ 함수에 인자가 전달됨을 볼 수 있다.
예를 들어 pList가 Person을 요소로 가진 리스트라고 하면 pList.sort()를 호출하면 Person 클래스에 정의되어있는 __it__ 메소드를 사용해서 정렬하게 될 것이다.
pList = [me, him, her]
for p in pList:
print(p)
pList.sort()
for p in pList:
print(p)
출력결과
Joy Kit
Jae Sung
Jyung Un Hyang
728x90
반응형
'파이썬' 카테고리의 다른 글
(파이썬) Grades 클래스 (0) | 2023.08.12 |
---|---|
(파이썬) 상속/Inheritance (0) | 2023.08.09 |
(파이썬) 추상 데이터 타입과 클래스 (0) | 2023.08.07 |
(파이썬) 예외 처리하기 (0) | 2023.08.06 |
(파이썬) 문자 번역하기 (0) | 2023.08.05 |