Introduction to Classes
왜 클래스라는 것을 사용하는 것인가?
파이썬은 객체지향(object-oriented) 프로그래밍 언어입니다. 객체지향 프로그래밍은 물체들(objects)라는 프로그래밍 구조를 다룬다는 의미입니다. object란 하나의 데이터 구조( 함수들)과 데이터를 포함한 물체의 함수들(Functions of an object)을 그것의 methods라고 일컫습니다.
my_dict.item()
다음 명령어를 수행하면 파이썬은 my_dict가 items()라는 method(모든 dictionaries가 기본적으로 내재되어있는 method입니다)를 가지고 있는지를 확인해 본 뒤, 그 method가 있는것을 확인하고 items에 대한 메소르르 실행시키고 그 값을 저희에게 알려주는 겁니다.
그러나 무엇이 "Eric"을 스트링으로 만들고 my_dict를 Dictionary로 정의하는 걸까요? 사실 이 둘은 ‘str’이라는 클래스와 ‘dict’라는 클래스의 instances에 불과합니다. 클래스란 비슷한 특성과 methods를 가진 objects들을 조직하고 생성하는 체계를 의미합니다.
Problem) Fruit라는 클래스를 정의하고, lemon이라는 instance 를 만든 코드입니다.
#Problem) Fruit라는 클래스를 정의하고 lemon이라는 instance 를 만든 코드입니다.
class Fruit(object):
def __init__(self, name, color, flavor, poisonous):
#여기서 self는 자기자신을 호출하기 위한 값으로 self가 아닌 다른 단어여도 무방
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
#init:initializer 생성자
#자기 자신이 어떠한 구조로 생성되는지를 나타내는 것으로 필수
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이라는 object 생성
lemon.description()
lemon.is_edible()
Class syntax
class NewClass(Class1):
새로운 클래스의 이름과 괄호 속 안에는 상속(inherits)받을 클래스를 포함합니다.
현재 NewClass는 Class1라는 클래스를 상속 받게 지정을 해놓았습니다.
class(클래스를 생성하겠다는 keyword) 새로운 클래스의 이름(상속 받을 클래스의 이름):
으로 구성됩니다. 유저에 의해 정의된 파이썬 클래스들은 관습적으로 대문자를 사용합니다.
class Animal(object):
pass
위 뜻은 object라는 클래스를 상속받는 Animal이라는 새로운 클래스를 정의하겠다는 뜻이며 pass라는 keyword는 아무기능도 수행하고 있지만 파이썬에게 의도적인 공백을 남기고 있다는 것을 뜻합니다. 만약 pass를 제외시키면 python은 오류를 생성하고 말죠
problem) daehyun 이라는 클래스를 정의해봅시다.
Classier Classes
클래스로 더 많은 기능을 할당하고 싶다면 ‘pass' keyword를 지우고 다른 것으로 대체해야합니다.
어쩌면 첫 연습에서 특이하게 생긴 함수 :__init__() 함수를 기억하셨을 수도 있을겁니다. 이 함수는 생성하려는 objects를 initialze 하는데에 사용됩니다. (언제나 필요)
__init__()함수는 언제나 1개 이상의 arguments를 필요로 합니다. 그 argument 는 self라고 부르며 이것은 생성된 object를 언급합니다. 여러분은 __init__() 함수를 클래스가 생성하는 각각의 objects를 생성하게 할 수 있습니다. 부팅하는 method라고 생각하시면 됩니다.
class Animal(object):
def __init__(self):
pass
하나를 더 수정해봅시다. 우리의 클래스의 첫 번째 object를 instantiate (create)해봅시다.
지금까지는 __init__() 함수가 오직 한 개의 argument를 갖게 설정을 했습니다. self는 사실 Python의 관습입니다. 굳이 self라고 설정하지 않아도 됩니다.하지만 압도적으로 __init__()함수에의 첫번째 parameter에는 self라고 쓰는 것이 보편적인지라 첫번째 argument는 self라고 지정해주는 것이 다른 사람이 코드를 이해하는데 편합니다.
파이썬에서는 __init__() 함수에서 받은 첫 번째 parameter(매개변수)를 생성된 object를 언급하는데 사용합니다. 이것이 self라고 지칭되는 이유죠, 이 매개변수 자체가 생성되는 object의 정체성을 결정짓는데 사용되기 때문입니다.
class Animal(object):
def __init__(self,name):
self.name = name
a=Animal("토끼")
print a.name #토끼
name이라는 두 번째 매개변수를 내려보내고 이것으로 생성하려는 오브젝트의 name이라는 특성에 초기값으로 넣어주는 상황입니다.
Instantiating Your First Object
Objects를 새로 생설할 시간이 되었습니다. 우리는 dot notation(.)을 활용해 우리의 objects의 특성들에 접근할 수 있습니다. 어떻게 활용되는 지 다음을 보시죠
class Square(object):
def __init__(self):
self.sides = 4
my_shape = Square()
print my_shape.sides #4
1. 우리는 sides라는 특성을 가진 Square라는 클래스를 생성했습니다.
2. Class 정의 밖에서, 우리는 새로운 Square의 new instance인 my_shpade를 생성했고 my_shape.sides로 특성에 접근했습니다.
problem)
class Animal(object):
def __init__(self,name):
self.name = name
zebra = Animal("Jeffrey")
print zebra.name #Jeffrey
Class definition
class Animal(object):
def __init__(self, name, age, hungry):
self.name = name
self.age = age
self.is_hungry = hungry
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
이제 어떻게 classes와 objects가 작동하는지를 보았습니다. __init__()와 self를 가지고 조작해보는 것도 좋은 방법입니다.
언급했던 대로, __init__()함수는 클래스의 instance object를 boots up 해줍니다. init비트는 initialize의 줄임말입니다.
__init__()의 첫 번째 매개변수는 instance obejct를 언급하는데 사용됩니다. 추가적인 arguments를 할당하여 생성하려는 오브젝트의 특성에 값으로 지정해줄 수 있습니다. 위에서는 age와 name 으로 할당을 해주었죠.
Class scope
a=3
def asd(a):
a=a+3
print a
return a
asd(a) #6
print a #3
asd 함수에서 a=6을 만들어줬는데,, 왜 print a 에서 3이라는 값이 나왔을까?
Python 클래스들에서 중요한 측면 중에 하나가 scope(범위)입니다.
파이썬에서 scope란 특정 변수가 프로그램 내에서 접근될 수 있는 지역의 범위를 의미합니다.
클래스를 다룰 때 언제나 어디서나 접근할 수 있는 변수들이 있고(Global variables), 특정 클래스의 멤버만 접근할 수 있는 변수들이 있고(Member variables), 한 클래스의 특정한 instances만 접근할 수 있는 변수들(instance variables)가 있습니다. 각각의 scope가 다른 것이죠.
이것은 변수만이 아니라 함수에 대해서도 마찬가지입니다. 어떤 함수는 항상 접근할 수 있고 또 어떤 함수는 특정 클래스의 멤버만, 또 어떤 것들은 특정 instance objects만 접근할 수 있지요.
class Animal(object):
is_alive = True #global variables 를 선언하는 위치
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
A Methodical Approach
특정 클래스가 함수를 내부에 품고 있을 때 그것을 methods라고 부릅니다. 이미 하나의 method를 보았습는데 __init__()함수죠. 물론 여러분이 자신만의 methods를 만들어낼 수도 있습니다.
class Animal(object):
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
problem) description이라는 method를 다음 Animal클래스에 추가해보십시오.
description은 오브젝트의 name와 age를 출력하면됩니다.
아무 오브젝트나 생성을 해주고, description method를 출력해주세요
class Animal(object):
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print self.name
print self.age
print self.is_alive
hippo = Animal("Anderson", 36)
hippo.description()
#Anderson
#36
#True
9. 클래스는 멤버 변수들(Member variables)를 갖을 수 있습니다. 멤버 변수들은 클래스의 모든 멤버들이 접근할 수 있는 것을 말합니다.
hippo = Animal("Jake", 12)
cat = Animal("Boots", 3)
print hippo.is_alive
hippo.is_alive = False
print hippo.is_alive
print cat.is_alive
class Animal(object):
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print self.name
print self.age
print self.is_alive
hippo = Animal("Jake", 12)
cat = Animal("Boots", 3)
print hippo.is_alive #True
hippo.is_alive = False
print hippo.is_alive #False
print cat.is_alive #True
위 예제에서 우리는 Animal의 2가지 instances를 생성했습니다.
우리가 True를 출력한 다음에 hippo's 의 is_alive를 False로 변경을 했습니다.
우리는 hippo만 변경했을 뿐 고양이의 것이 변경되지 않는 걸 볼 수 있습니다.
class Animal(object):
is_alive = True
health = "good"
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print self.name
print self.age
hippo = Animal("Anderson", 36)
hippo.description()
sloth = Animal("hoseok", 29)
ocelot = Animal("hoseok2", 29)
print hippo.health
print sloth.health
print ocelot.health
#Anderson
#36
#good
#good
#good
이번에는 쇼핑 상황에 대해서 정의를 해보죠.
problem)
다음의 코드를 이해하고 ShoppingCart의 instance를 my_cart로 생성합시다. 좋아하는 여러 값들을 initialize하시고, 그 이후에 여러분의 카트에 추가하는 add_item method를 이용해보세요
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
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):
"""카트에서 물품을 빼내느 것"""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."
sol)
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
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):
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("hoseok")
my_cart.add_item("hoseok2", 10)
#hoseok2 added.
Inheritance
inheritance는 한 클래스가 다른 클래스의 특성과 methods를 흡수하는 프로세스를 의미합니다. 그리고 이것은 is-a relationship으로도 표현 됩니다. 예를들어 Panda is a bear. 라는 것은 Panda가 Bear Class를 상속할 수 있다는 것을 뜻합니다. 그러나 벤츠차는 트랙터가 아니듯, 이 경우 벤츠는 트랙터 클래스를( 물론 이들이 많은 특성과 함수가 공통점을 갖고 있을지라도) 상속 받아선 안됩니다. 하지만 벤츠나 트랜터나 ‘운송수단’이라는 클래스를 상속 받을 순 있겠죠.
ex)
# -*- encoding:utf-8-*-
class Customer(object):
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print "shopping cart 속에서 발현된 문장입니다."
class ReturningCustomer(Customer):
def display_order_history(self):
print "오더 히스토리를 보여드리겠습니다."
monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()
#shopping cart 속에서 발현된 문장입니다.
#오더 히스토리를 보여드리겠습니다.
상속 받은 부분을 풀어쓰면 밑과 같다
class ReturningCustomer(): 부분
# -*- encoding:utf-8-*-
class Customer(object):
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print "shopping cart 속에서 발현된 문장입니다."
class ReturningCustomer():
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print "shopping cart 속에서 발현된 문장입니다."
def display_order_history(self):
print "오더 히스토리를 보여드리겠습니다."
monty_python = ReturningCustomer("ID: 12345")
print monty_python.customer_id
monty_python.display_cart()
monty_python.display_order_history()
#ID: 12345
#shopping cart 속에서 발현된 문장입니다.
#오더 히스토리를 보여드리겠습니다.
Inheritance Syntax
상속의 기본구조는 다음과 같습니다.
class DerivedClass(BaseClass):
# code goes here
DerivedClass는 BaseClass를 상속하는 새로운 class를 생성하는 것입니다.
problem) 아래의 Shape를 상속받는 Trinage이라는 클래스를 생성해주세요. 이니셜라이저로 side1,side2,side3의 길이
HoseokTriangle = Triangle(3,4,5) #변의 길이를 넣고
print HoseokTriangle.side1
#3
print HoseokTriangle.side1
#4
print HoseokTriangle.side1
#5
이렇게 값이 나오도록 정의를 해봅시다.
class Shape(object):
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
sol)
class Shape(object):
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
class Triangle(Shape):
def __init__(self,side1,side2,side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
HoseokTriangle = Triangle(3,4,5)
print HoseokTriangle.side1
print HoseokTriangle.side2
print HoseokTriangle.side3
Override
가끔 여러분은 상속 받은 특성을 사용하지 않고 자신만의 특성으로 개조하고 싶은 마음이 있을겁니다.
class Employee(object):
def __init__(self, name):
self.name = name
def greet(self, other):
print "Hello, %s" % other.name
class CEO(Employee):
def greet(self, other):
print "Get back to work, %s!" % other.name
ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
# Hello, Emily
ceo.greet(emp)
# Get back to work, Steve!
우리의 CEO를 위해 greet_underling method를 사용하진 않고 greet method를 override 시켰습니다. 이 방식으로 우리는 다른 사람에게 어떻게 인사하는지는 알 수 없습니다.
super call
반대로 보면 상속을 받은 클래스를 가지고 overwrite 되었다는 사실을 깨닫곤 할겁니다. 파이썬에 내재된 super call 을 이용해 superclass의 특성과 methods에 접근할 수 있습니다.
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
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 Triangle(object):
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
16.Class it up
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):
if (self.angle1 + self.angle2 + self.angle3) == 180:
return True
else:
return False
17. Instantiate an Object
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):
if (self.angle1 + self.angle2 + self.angle3) == 180:
return True
else:
return False
my_triangle = Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()
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):
if (self.angle1 + self.angle2 + self.angle3) == 180:
return True
else:
return False
class Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 = self.angle
self.angle2 = self.angle
self.angle3 = self.angle
다시 복습
1. Class basics
클래스들은 methods와 variables들을 가진 복잡한 objects들을 저장하는데 유용합니다. 클래스를 정의한다는 것은 함수(Function)을 정의하는 것과 매우 유사합니다. 그러나 class keyword를 대신 사용할 뿐이죠. 우리는 object class를 상속 받는데 쓰기 위해서 괄호 안에 object라는 단어를 사용합니다. 이 말은 우리의 클래스가 'object'라는 클래스의 모든 특성을 상속 받았다는 것을 뜻합니다. object 클래스는 가장 심플하고 기본적인 클래스죠. 우리는 추후에 클래스들이 다른 것을 상속받을 수 있음을 알아볼 겁니다. 완전히 빈 클래스는 다음과 같은 모습을 가집니다.
class ClassName(object):
# class statements go here
class Car(object):
pass
2. Create an instance of a class
우리는 새로운 objects(그 클래스들의 instances라고 부르는)를 사용하기 위해 클래스들을 이용할 수 있습니다.
클래스의 새로운 instance 를 생성하는 것은 아래와 같이 표현할 수 있습니다.
새로운 Object = 클래스네임()
class Car(object):
pass
my_car = Car()
3. Class member variables
클래스들은 member varables(각각의 클래스 객체(class object)에 대한 정보를 갖고있는)를 가질 수 있습니다. 우리는 그들을 Member varibales라고 부릅니다. 왜냐면 그것들은 class object에 포함되는 정보들이기 때문입니다.
class Car(object):
condition = "new"
my_car = Car()
4. Calling class member variables
우리가 만든 각각의 class object는 그들만의 멤버 변수들을 갖고 있습니다. 우리는 my_car Car class의 instance를 생성했기 때문에 my_car는 이미 condition이라는 멤버 변수를 갖고 있습니다. 이 특성은 my_car가 생기는 순간 부터 할당 받게 됩니다.
class Car(object):
condition = "new"
my_car = Car()
print my_car.condition #new
5. Initializing a class
__init__()는 우리가 새로운 클래스의 새로운 instance를 만들 때 호출되는 특별한 함수입니다. 우리는 보지 못하더라도, 이것은 기본적으로 존재합니다. 하지만 우리는 우리만의 __init__() 함수를 클래스 안에 만들어서 기존 버전을 overwriting 할 수 있습니다. 우리는 다른 함수들과 같이 더 많은 입력 변수들을 제공하기 위해 사용할 수 있습니다.
__init__()함수로 보내지는 첫 번째 매개변수는 언제나 self( keyword )로 할당이 됩니다. 이는 내부적으로 object가 자기 자신을 추적하는데 사용하는데에 쓰이는 개념을 의미합니다. 우리는 추가적인 변수들을 더 보내줄 수 있습니다.
멤버 변수들을 생성하며 클래스에 변수를 할당하기 위해 우리는 dot notation(.)을 이용할 수 있습니다. 예를 들어 새로운 변수를 클래스안에 집어넣어주고 싶다면
self.new_variable = new_variable 과 같이 할당할 수 있습니다.
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.condition #new
6. Referring to member variables
클래스 멤버 변수를 부르는 것은 그 값들이 클래스 안에서 생성되었거나 __init__ 함수를 통해 initialization이 되었던 간에 똑같이 작동을 합니다. 우리는 클래스들의 멤버 변수를 dot notation(.)을 이용해 접근합니다. 그 변수들이 그 객체 않에 포함되어 있기 때문입니다.
예를 들어서, 우리가 new_object라는 특정 클래스의 새로운 instance에 대해 new_variable이라는 멤버 변수를 변수를 만들었다고 한다면, 다음 문장을 통해 접근할 수 있습니다.
new_object.new_variable
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.model
print my_car.color
print my_car.mpg
#new
#DeLorean
#silver
#88
7. Creating class methods
멤버 변수들 말고도 클래스들은 자신만의 methods를 가질 수 있습니다. 예를 들어서
class Square(object):
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
perimeter() class method는 Square 클래스의 정의에 쓰여진다는 것만 제외하면 다른 함수들과의 정의 방법과 같습니다.
우리가 __init__()함수를 정의할 때와 마찬가지로 여러분은 첫번째 멤버 변수를 class method의 self로 제공을 하게 됩니다.
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
my_car.display_car()
#This is a silver DeLorean with 88 MPG.
8. Modifying member variables
우리는 클래스 내의 다른 멤버 변수들을 initialize 시켰던 방법과 마찬가지로 변수들을 수정할 수 있습니다. 이것은 우리가 변수가 class method 안에서 발생하는 특별한 것에 기반한 한 변수가 가진 값을 변경하는데 유용합니다.
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
#new
#used
9. Inheritance(상속)
클래스들의 이득 중의 하나는 우리가 parent classes를 상속받아 더 복잡한 클래스들을 생성할 수 있다는 점입니다. child classes에 추가적으로 변수들과 methods들을 포함시킬 수 있기 때문에 이러한 방식이 우리의 시간을 절약시켜주고 더 복잡한 objects를 구성하는데 도움을 줍니다.
우리는 child 클래스를 parent 클래스로 부터 모든 변수와 함수들을 상속받는 클래스라고 정의하고 있습니다. 말하자면
class ChildClass(ParentClass):
라고 볼 수가 있죠. 일반적으로 우리는 'object'를 부모(parent) 클래스로 이용합니다. 왜냐면 클래스의 가장 기본적인 유형이기 때문입니다. 그러나 다른 클래스들로 특정함으로서 우리는 더 복잡한 기능을 상속 받을 수 있습니다.
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")
10. Overriding methods
ElectricCar가 Car의 유형보다 좀 더 세분화가 되어있기 때문에, 우리는 drive_car() method에 다른 유형의 기능성을 추가해봅시다.
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
def drive_car(self):
self.condition = "like new"
my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")
print my_car.condition
my_car.drive_car()
print my_car.condition
#new
#like new
11. Building useful classes
여러분은 차라는 클래스들을 실제 세계에서 디자인 할 기회는 흔치 않지만, 클래스들은 추상적인 데이터들을 모으고 접근하는데에 매우 유용합니다.
override 하는데 한 가지 유용한 class method가 __repr_() 라는 메소드입니다. 이는 representation의 짧은 줌말인데, 이 method에 반환 값(return value)를 제공함으로서, 우리의 클래스의 object가
One useful class method to override is the built-in __repr__() method, which is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a print statement).
class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point
#(1,2,3)
'컴퓨터 언어 > python' 카테고리의 다른 글
파이썬 기초 4 (0) | 2020.07.15 |
---|---|
Python 8. Battleship game (0) | 2020.07.15 |
Python 7. LOOP (0) | 2020.07.15 |
파이썬 기초1 (0) | 2020.07.15 |
Python 5: List + Dictinaray + for루프 (0) | 2020.07.14 |