李旺陽
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Class slide ver. bearrrrrrro 2020/5/23 sylveon 2021/5/7 修改 --- ## 語法 ```python class ClassName: pass ``` ---- 加上一些東西 ```python class Computer: pass cp_1 = Computer() cp_1.cpu = 'i5-8750' cp_1.size = 14 cp_1.price = 20000 cp_2 = Computer() cp_2.cpu = 'i7-1450' cp_2.size = 10 cp_2.price = 2000 ``` ---- 試試看 ```python print(cp_1) print(cp_1.cpu) print(cp_2.price) ``` --- ## 作用 ![](https://i.imgur.com/hYayTVd.jpg) ---- * 好懂 * 易讀 * 減少重複性高的程式碼 * 看起來比較專業 XD ---- ## 概念 * 可以發揮你的想像力做出幾乎任何東西 * 自定義物件(資料型態?) * 當你想把某些狀態(資料)和功能(函式)綁在一起時,class是一個好選擇 ---- ## 一些不知道不影響你打code但是知道比較好的東西 * class 又稱為「類別」 * class 底下的資料又稱為「屬性」 * class 底下的函式又稱為「方法 (method)」 ---- ### 更多簡單的範例 電腦 ```python class Computer: def __init__(self, cpu, size, price): self.cpu = cpu self.size = size self.price = price ``` * 其中`__init__`是比較特殊的函式,會在「建構物件」時自動呼叫(後面有範例) * 這裡的 `xxx.yyy`指"xxx的yyy",有點類似之前在import一些工具中的用法 ---- 人 ```python class Person: def __init__(self, name, height, weight): self.name = name self.height = height # cm self.weight = weight # kg def get_bmi(self): return self.weight / (self.height / 100) ** 2 ``` ---- baba ```python class Baba: def __init__(self, x, y): self.x = x self.y = y def up(self): self.x -= 1 def down(self): self.x += 1 def left(self): self.y -= 1 def right(self): self.y += 1 ``` ---- **Remark:** class中的函式第一個參數要放self,不然可能會噴錯或是發生奇怪的事情(? ---- **Remark:** `__init__`中參數的名稱可以任意,像是我也可以這樣寫 ```python class Animal: def __init__(self, x): self.name = x ``` 但名稱不一致可能造成混淆而且沒有必要,除了可以少打幾個字以外沒有任何好處 ![](https://i.imgur.com/L87dxc9.png) --- ## 用class ---- ### Instance Instance 又稱為「實體」,依照class真的某個東西做出來 | Class | Instance | | -------- | -------- | | 設計圖 | 真正的東西 | ---- 有了class以後,我們可以造出多個狀態和功能類似的東西 ![](https://i.imgur.com/2mwu3q2.gif) ---- ```python cp_1 = Computer('i5-8750', 14, 20000) cp_2 = Computer('i7-1450', 10, 2000) print(cp_1) print(cp_1.cpu) print(cp_2.price) ``` ---- ```python bearrrrrrro = Person('bearrrrrrro', 170, 71) print(bearrrrrrro.name) print(bearrrrrrro.get_bmi()) ``` --- ## 連連看 ![](https://i.imgur.com/kaBbOjg.png) ---- [解答](https://i.imgur.com/PPL9Hgg.png) --- ## 練習1 小明不小心把墨水打翻在他的code上,請幫小明通靈被墨水蓋掉的資訊 ```python class Student: def __init__(self, name, math, english, chinese): 墨墨墨墨墨 墨墨墨墨墨 墨墨墨墨墨 墨墨墨墨墨 def average(墨墨墨墨墨墨 墨墨墨墨墨 # 回傳三科的平均值 def is_pass(墨墨墨墨墨墨 墨墨墨墨墨 # 每一科都不低於60分就回傳true boss = Student('Sophia', 80, 100, 100) print(boss.average()) print(boss.is_pass()) ``` ---- ```python class Student: def __init__(self, name, math, english, chinese): self.name = name self.math = math self.english = english self.chinese = chinese def average(self): return sum((self.math, self.english, self.chinese)) / 3 # 回傳三科的平均值 def is_pass(self): return min((self.math, self.english, self.chinese)) >= 60 # 每一科都不低於60分就回傳true boss = Student('Sophia', 1000, 100, 100) print(boss.average()) print(boss.is_pass()) ``` --- ## 特殊方法(補充) + 練習2 ```python from math import gcd class Rational: def __init__(self, p, q): t = gcd(p, q) p, q = p // t, q // t self.p = p self.q = q def __str__(self): return '{}/{}'.format(self.p, self.q) def __add__(self, a): # print('{} + {}'.format(self, a)) nu = self.p * a.q + a.p * self.q di = self.q * a.q com = gcd(nu, di) return Rational(nu // com, di // com) # Your part here!! def __sub__(self, a): # x - y # print('{} - {}'.format(self, a)) pass def __mul__(self, a): # x * y # print('{} * {}'.format(self, a)) pass def __truediv__(self, a): # x / y # print('{} / {}'.format(self, a)) pass def __eq__(self, a): # x == y # print('{} == {}'.format(self, a)) pass if __name__ == '__main__': r = Rational(1, 4) s = Rational(3, 8) t = Rational(2, 8) print(r + s) print(r - s) print(r * s) print(r / s) print(r == s) print(r == t) ``` ---- 解答 ```python from math import gcd class Rational: def __init__(self, p, q): t = gcd(p, q) p, q = p // t, q // t self.p = p self.q = q def __str__(self): return '{}/{}'.format(self.p, self.q) def __add__(self, a): # print('{} + {}'.format(self, a)) nu = self.p * a.q + a.p * self.q di = self.q * a.q com = gcd(nu, di) return Rational(nu // com, di // com) # Your part here!! def __sub__(self, a): # x - y # print('{} - {}'.format(self, a)) nu = self.p * a.q - a.p * self.q di = self.q * a.q return Rational(nu, di) def __mul__(self, a): # x * y # print('{} * {}'.format(self, a)) nu = self.p * a.p di = self.q * a.q return Rational(nu, di) def __truediv__(self, a): # x / y # print('{} * {}'.format(self, a)) nu = self.p * a.q di = self.q * a.p return Rational(nu, di) def __eq__(self, a): # x == y # print('{} == {}'.format(self, a)) return self.p == a.p and self.q == a.q if __name__ == '__main__': r = Rational(1, 4) s = Rational(3, 8) t = Rational(2, 8) print(r + s) # Ratinal.__add__(r, s) print(r - s) print(r * s) print(r / s) print(r == s) print(r == t) ``` --- ## 繼承(補充) ![](https://i.imgur.com/oJzZthn.png) ---- ```python class Dog: def __init__(self, name, color): self.name = name self.color = color def sound(self): print("Woof") class Cat: def __init__(self, name, weight): self.name = name self.weight = weight class Vampire: def __init__(self, name, age): self.name = name self.age = age def sound(self): print("Wryyyyyyyy!!") def time_stop(self): print("Za warudo!") ``` ---- Same! ```python class Animal: def __init__(self, name): self.name = name def hello(self): print(self.name) class Dog(Animal): def __init__(self, name, color): super().__init__(name) self.color = color def sound(self): print("Woof") class Cat(Animal): def __init__(self, name, weight): super().__init__(name) self.weight = weight class Vampire(Animal): def __init__(self, name, age): super().__init__(name) self.age = age def sound(self): print("Wryyyyyyyy!!") def time_stop(self): print("Za warudo!") ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully