전기전자공학부
2018142125
조정빈
class Normal:
def __init__(self, mileage):
"""
처음에 객체가 가지고 있을 mileage를 주어주며 initialize
"""
self.mileage = mileage
def __str__(self):
"""
객체를 print하면 해당 객체의 mileage를 알려줌
"""
return "mileage = {}".format(self.mileage)
def _calc(self, amount):
"""
normal class 들은 mileage + amount
"""
self.mileage = self.mileage + amount
return self.mileage
def deposit(self, amount):
return self._calc(amount)
class Vip(Normal):
def _calc(self, amount):
"""
Normal class는 ㅜNormal class를 상속 받아 _calc 함수를 overriding함
Vip class 들은 mileage + amount*2
"""
self.mileage = self.mileage + amount*2
return self.mileage
Normal class는 class 변수로 마일리지를 가지고 있고 class 함수로 calc과 deposit이 있다. 이를 Vip가 상속하여 _calc함수를 overriding하여 vip 객체에 deposit을 부르는 것과 normal객체에 deposit을 쓰는것이 다르게 된다.
from math import sqrt
class Point:
def __init__(self, x=0, y=0):
"""
Point class 객체를 생성할 때 x,y를 주며 initialize
"""
self.x = x
self.y = y
def __str__(self):
"""
print 함수를 통해 객체를 print하면 point출력
"""
return "({0},{1})".format(self.x, self.y)
def __eq__(self, other):
"""
위치가 같으면 True 다르면 False 반환
"""
if self.x == other.x and self.y == other.y:
return True
else:
return False
def distance(self, other):
"""
self와 other사이의 거리를 반환하는 함수
"""
return sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
Point 라는 class는 자기 자신의 x좌표와 y좌표를 class 변수로 갖는다. 새로운 class를 정의 할 때에는 해당 class의 객제끼리 비교를 위해 eq() 함수를 정의해야 하는데, point가 같기 위해서는 두개의 point의 x,y값이 같아야 하므로 이와 같이 구현하였다. 또한 class function중 하나인 distance fucntion은 한 점에 대해 다른 점 사이의 거리를 반환해주는 함수이다.
class Unit:
def __init__(self, name, health):
self.name = name
self.health = health
def __str__(self):
"""
객체를 print시 이름과 생명력 print
"""
return "{0} health : {1}".format(self.name, self.health)
def damaged(self, amount):
#데미지는 받으면 무조건 생명력이 까임
self.health = self.health - amount
#까인 생명력이 0보다 작으면 죽었다 출력
if self.health <= 0 :
return "{} destroyed".format(self.name)
#까인 생명력이 0 보다 크면 남은 생명력 출력
else:
return "{0} : {1}".format(self.name,self.health)
class Magician(Unit):
def __init__(self, name, health, energy):
"""
Unit을 상속받음
"""
super().__init__(name, health)
self.energy = energy
def __str__(self):
"""
객체를 print시 이름과 생명력, 에너지 print
"""
return "{0} : {1}({2})".format( self.name , self.health,self.energy)
def skill(self, amount):
#에너지가 부족하면 스킬을 못쓰고 못쓴다고 출력
if self.energy < amount :
return "Not enough energy"
#에너지가 충분하면 스킬을 쓰고 남은 에너지 출력
else:
self.energy = self.energy - amount
return "{} energy left".format(self.energy)
Unit이라는 class를 Magician class가 상속하는 코드이다. Unit은 클래스 변수가 이름과 생명력이 있는데 추가적으로 magician은 이외에 에너지가 존재한다. 때문에 magician은 unit의 모든 클래스 변수와 클래스 함수를 사용하지만 추가적으로 에너지에 관한 함수와 변수가 필요하다. 때문에 unit을 상속하여 unit의 모든 클래스 함수와 클래스 변수를 활용하며 추가로 에너지와 에너지에 관한 클래스 함수를 활용한다.
구현하는 과정에서 신경 썻던 부분은 skill을 쓸 때와 damage를 받았을 때는 다르다는 것이다. skill을 쓸때 에너지가 부족하면 skill을 아예 쓰지 못하지만 damage를 받을 때는 health가 damage보다 작더라도 우선 damage를 받고 죽으므로 두 함수의 코드를 똑같은 방식으로 짜면 안된다.
class Student:
def __init__(self, first_name, last_name, height):
self.first_name = first_name
self.last_name = last_name
self.height = height
def __str__(self):
return "{0} {1}".format(self.first_name, self.second_name)
def __add__(self, other):
return self.height + other.height
def __eq__(self, other):
if self.height is other.height:
return True
else:
return False
def __lt__(self, other):
#x < y operation을 custom class에 대해 정의할 수 있는 함수
return self.height < other.height
def __le__(self, other):
#x<=y operation을 custom class에 대해 정의할 수 있는 함수
return self.height >= other.height
def get_id(self):
id = 2021000000+ord(self.first_name[0])*1000 + ord(self.last_name[0])
id = id + sum([ord(a) for a in self.first_name+self.last_name])
return id
first_name, last_name, height를 class변수로 갖는 student class이다. add() 함수는 덧셈을 정의하는 함수를 overriding하여 커스텀 클래스의 덧셈을 정의 할 수 있도록 해준다. 이와 같이 eq()는 equal operation을 overriding하여 커스텀 클래스에서 커스텀한 equal operation을 정의할 수 있도록 해준다. def lt(self, other): ,def le(self, other): 도 마찬가지이다. 각각 x<y operation, x≤y operation을 overriding 한다.