프리렉 - FREELEC
http://freelec.co.kr/book/catalogue_view.asp?UID=134
이강성저
책 391-392 참조
책 13.4.1 참조
책 13.3.1 참조
class B:
b = 2
class C(B):
a = 1
def f(self):
self.a = 5
c1 = C()
c2 = C()
c1.f()
가)
c1.a
c2.a
나)
이름 공간은 다음과 같이 연결되어 있다.
object - B - C - c1
+- c2
다)
c1.a를 통하여 우선 c1 이름공간에 a가 있는지 살핀다. c1에 없다면 클래스 C 이름 공간에서 a를 찾는다(발견된다). 만일 여기서도 찾지 못하면 B 에서 a를 찾는다. B에서도 못 찾으면 object에서 찾는다. 그래도 없으면 NameError 발생한다.
import time
class LifeSpan:
def __init__(self): # 생성자
self._start_time = time.time()
def __del__(self): # 소멸자
print(time.time() - self._start_time)
life = LifeSpan()
time.sleep(2)
del life
from math import *
class Turtle:
def __init__(self):
self.x = 0.0
self.y = 0.0
self.heading = 0.0
def turn(self, angle):
self.heading = (self.heading + angle) % 360
def forward(self, distance):
rad = radians(self.heading)
dx = distance * cos(rad)
dy = distance * sin(rad)
self.x += dx
self.y += dy
def pos(self):
return self.x, self.y
def almostEqual(a, b):
return abs(a-b) < 1e-7
def almostEqual2(a, b):
return abs(a[0]-b[0]) < 1e-7 and abs(a[1]-b[1]) < 1e-7
t = Turtle()
t.forward(100)
assert almostEqual2(t.pos(), (100, 0))
t.turn(90)
t.forward(100)
assert almostEqual2(t.pos(), (100, 100))
t.turn(90)
t.forward(100)
assert almostEqual2(t.pos(), (0, 100))
t.turn(90)
t.forward(100)
assert almostEqual2(t.pos(), (0, 0))
t = Turtle()
t.turn(45)
t.forward(100)
assert almostEqual2(t.pos(), (100/sqrt(2), 100/sqrt(2)))