Object 是一個 data abstraction 可得到
產生 instance of object 第一步
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
__init__
是一個特殊的methodself
是 參照這個class產生的instancex, y
是 Coordinate這個 object的初始data
c = Coordinate(3,4)
origin = Coordinate(0.0)
print(c.x)
print(origin.x)
c的例子中,x=3, y=4, 而self就是c自己,python自己會知道,不用寫上去。
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
self.x 就是去拿這個instance的data attribute
使用 distance
c = Coordinate(3,4)
zero = Coordinate(0.0)
print(c.distance(zero)) -- conventional
print(Coordinate.distance(c,zero))
def __str__(self)
methodisinstance(c, Coordinate)
__add__
self + otherclass Fraction(Object):
def __init__(self, num, denum):
assert type(num) == int ans type(denum) == int
self.num = num
self.denum = denum
def __add__(self, other):
top = self.num*other.denum + self.denum*other.num
bott = self.denum*other.denum
return Fraction(top, bott)