Intro to OOP

Object-Oriented Programming(OOP), 物件導向程式設計:在Python中所有datatype都是物件(str, int, list, set, dict….)。本章將教學如何自制datatype, 一個物件可以把properties(屬性)跟behaviors(行為)綁定到獨立的物件上, 例如:一台車的properties(出產年份, 價格), behavior(左轉, 右轉) ; 一個list的properties(.len()), behavior(.append())。

Class

A class is a code template for creating objects.

用來創照物件的模板, 可以想像是我們自己創造新的datatype ; Class 的命名習慣為開頭第一個字大寫。

Untitled

class Robot:
    pass

my_robot = Robot()
print(type(my_robot))
# <class '__main__.Robot'>

init() and Method

class Robot:
		# in classes,we can also define docstring
		"""Robot class is for creating robots"""
    # constructor
    def __init__(self, inputname, inputage):
        self.name = inputname
        self.age = inputage

my_robot_1 = Robot("Wilson", 25)
my_robot_2 = Robot("Grace", 26)
print(my_robot_1.name) # Wilson
print(my_robot_1.age) # 25
print(my_robot_1.age < my_robot_2.age) # True
print(my_robot_1.__doc__) # Robot class is for creating robots

class Robot:
		# in classes,we can also define docstring
		"""Robot class is for creating robots"""
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

		def walk(self):
        print(f"{self.name} is walking...")

		def sleep(self, hours):
        print(f"{self.name} is going to sleep for {hours} hours.")

my_robot_1 = Robot("Wilson", 25)
my_robot_2 = Robot("Grace", 26)

my_robot_1.walk() # Wilson is walking...
my_robot_1.sleep(15) # Wilson is going to sleep for 15 hours.

Class Attribute

以下的Robot舉例, 若在所有的Robot裡面有共享的屬性(ex: ingredient 都為 metal的話), 其中一種方法可以直接寫在__init__裡, 但這樣每做出一個Robot皆會出現, 若有大量的Robot則會有浪費記憶體的問題, 因此另一種方法則是可以直接做成class attribute(直接寫在class裡面), 他會屬於class本身而不會屬於每個object, 獲取class attribute的方法有以下3種:

  1. self.class.attribute (inside method definition)
  2. objectname.attribute (outside method definition)
  3. classname.attribute (try not to use this in method definition 原因如下)