iT邦幫忙

1

Python Object Oriented Programming - 1

  • 分享至 

  • twitterImage
  •  

本文為 MIT open course 影片心得
Yes

What are Object?

Object 是一個 data abstraction 可得到

  1. 內部表現 - 透過 data 屬性
  2. 與別的object作用的介面 - 透過 method (function) 表現行為但把實作藏起來

Defining how to create an instance of a class

產生 instance of object 第一步

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

__init__ 是一個特殊的method
self 是 參照這個class產生的instance
x, y 是 Coordinate這個 object的初始data

Actually creating an instance of a class

c = Coordinate(3,4)
origin = Coordinate(0.0)
print(c.x)
print(origin.x)

c的例子中,x=3, y=4, 而self就是c自己,python自己會知道,不用寫上去。

Define a method for the class

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))

其他特性

  • print(object) call def __str__(self) method
  • check the object of which class isinstance(c, Coordinate)
    _ __add__ self + other

舉例 Fraction class 實作 add

class 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)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言