# 01 왜 클래스(Class)를 사용하나요?
class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print ("I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor))
def is_edible(self):
if not self.poisonous:
print ("Yep! I'm edible.")
else:
print ("Don't eat me! I am super poisonous.")
lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()
I'm a yellow lemon and I taste sour. Yep! I'm edible.
# 02 클래스(Classes) 문법
class Animal(object):
pass
# 03 클래스(Classes)다운 클래스
class Animal(object):
def __init__(self):
pass
# 04 두 번째 매개변수 추가하기
class Animal(object):
def __init__(self, name):
self.name = name
# 05 첫번째 객체(Object) 인스턴스화
class Animal(object):
def __init__(self, name):
self.name = name
zebra = Animal("Jeffrey")
print (zebra.name)
Jeffrey
# 06 함수 __init__()과 self 더 알아보기
# Class definition
class Animal(object):
"""Makes cute animals."""
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry
# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.
zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)
print (zebra.name, zebra.age, zebra.is_hungry)
print (giraffe.name, giraffe.age, giraffe.is_hungry)
print (panda.name, panda.age, panda.is_hungry)
Jeffrey 2 True Bruce 1 False Chad 7 True
# 07 클래스 범위(Class Scope)
class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
zebra = Animal("Jeffrey", 2)
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)
print (zebra.name, zebra.age, zebra.is_alive)
print (giraffe.name, giraffe.age, giraffe.is_alive)
print (panda.name, panda.age, panda.is_alive)
Jeffrey 2 True Bruce 1 True Chad 7 True
# 08 메소드(method)
class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def description(self):
print (self.name)
print (self.age)
hippo = Animal("fanfank", 22)
hippo.description()
fanfank 22
# 09 멤버 변수(member variables) 추가하기
class Animal(object):
"""Makes cute animals."""
is_alive = True
health = "good"
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def description(self):
print (self.name)
print (self.age)
hippo = Animal("CHN", 5000)
sloth = Animal("JPN", 3000)
ocelot = Animal("USA", 300)
print (hippo.health)
print (sloth.health)
print (ocelot.health)
good good good
# 10 보다 현실적인 클래스와 객체
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print (product + " added.")
else:
print (product + " is already in the cart.")
def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print (product + " removed.")
else:
print (product + " is not in the cart.")
#
my_cart = ShoppingCart("fanfank")
my_cart.add_item("BaiduTieba", 1)
my_cart.remove_item("BaiduTieba")
BaiduTieba added. BaiduTieba removed.
# 11 경고: 상속(Inheritance)의 주의 사항
class Customer(object):
"""Produces objects that represent customers."""
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print ("I'm a string that stands in for the contents of your shopping cart!")
class ReturningCustomer(Customer):
"""For customers of the repeat variety."""
def display_order_history(self):
print ("I'm a string that stands in for your order history!")
#
monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()
I'm a string that stands in for the contents of your shopping cart! I'm a string that stands in for your order history!
# 12 상속(Inheritance) 문법
class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
# Add your Triangle class below!
class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
#
tri = Triangle(2,3,4)
tri.side1
tri = Shape(5)
tri.number_of_sides
5
# 13 오버라이드(Override)!
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
#
emp = Employee('John')
tmp = PartTimeEmployee('Tom')
print (emp.calculate_wage(10))
print (tmp.calculate_wage(10))
200.0 120.0
# 14 This Looks Like a Job For
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee("milton")
print (milton.full_time_wage(10))
200.0
# 15 클래스(Class)의 기초
class Triangle(object):
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
#
t = Triangle(1,2,3)
t.angle1
1
# 16 속성(attribute)과 메소드(method) 추가하기
class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
return (self.angle1 + self.angle2 + self.angle3) == 180
#
t = Triangle(3,4,5)
print (t.number_of_sides)
print (t.check_angles())
3 False
# 17 객체(Object) 인스턴스화(Instantiatie) 시키기
class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
return (self.angle1 + self.angle2 + self.angle3) == 180
my_triangle = Triangle(60, 60, 60)
print (my_triangle.number_of_sides)
print (my_triangle.check_angles())
3 True
# 18 상속
class Triangle(object):
number_of_sides = 3
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
return (self.angle1 + self.angle2 + self.angle3) == 180
class Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 = self.angle2 = self.angle3 = self.angle
my_triangle = Equilateral()
print (my_triangle.number_of_sides)
print (my_triangle.check_angles())
3 True