內容 / 重點 / 注意事項 / 其他或補充

sample code https://github.com/arthas989/python2022

Object-Oriented Programming (OOP)

補充唸法:double underscore = dunder

Chapter 6 - Object Oriented Programming
91. Intro to OOP Object-Oriented Programming (OOP)
是一種方法將properties和behaviors綁定到individual objects
背:A class is a code template for creating objects.
class的命名規則第一個字元用大寫
class的method與self關鍵字
我以為self代表的是class,原來不是?
要注意何時需要使用self,何時不用
(例如只是要存取傳入的參數,就不用使用self)
看92-2.py

properties/attributes/behaviors constructor 建構式/子 __init__ doctring的使用方式Object_name.__doc__

class Robot: “””doctring here””” # constructor 建構式/子 __init__

Object_name.__doc__

★同一個class裡的內容都要有____indentation ★class裡def的parameter第一個都要是self(除非是@staticmethod或@classmethod) ★class裡def的parameter不要放self.parameter

補充: https://www.maxlist.xyz/2021/01/11/python-object/ https://www.learncodewithmike.com/2020/01/python-class.html https://www.cnblogs.com/wangjian941118/p/9360471.html | | 92. Class Attribute, Static Method and Class Method | self.__class__.attribute (class inside用) 可以拿來存取修改class公用的attribute Object_Name.attribute (class outside用) Class_name.attribute (建議使用 cls取代)

class裡面的function 要indentitaion

@staticmethod

@classmethod | | 93. Quick Note | class裡的一般method與 @classmethod有什麼不同? | | 94. Inheritance | 繼承 「人class」-【properties】:ID、姓名、性別、年紀…… -【behaviors】:吃、睡…… base / parent class

寫學校系統 「學生class」、「老師class」繼承「人class」用法:class Student(People): child / derived class

就不用再重寫共同的properties、behaviors,只要寫特有的method 但在做init時要設定parent的properties,傳值到parent的init 用Class_name.__init__(self,name,age) 可以用super().__init__(name,age) 取代,就不用用self關鍵字 code

覆寫method: ★注意要提供需要的child class的parameter | | 95. Multiple Inheritance | Multiple Inheritance: JAVA / JAVASCRIPT (X) C++ (O) 複雜一般會避免使用 Python (O),Child(Parent_A,Parent_B)

multiple inheritance示範 95-1.py

如何多重繼承有相同method 當呼叫時會執行哪個呢? method resolution order (MRO) 方法解析順序 依據depth-first graph traversal 95-2.py 能走多深先走多深,找不到就退回一格看有沒有其他路 A,B,E,F,C,D,G classname.mro() EX:print(A.mro()) 使用classname,不是instance_name classname.__mro__ EX:print(A.__mro__) 缺:不能直接就用眼睛看出在表達什麼 → 不好維護 優:要同時繼承很多個class時要層層繼承 |