Python物件導向OOP
物件(Object)是類別(Class)的實例(Instonce)
ex: 車子 => 類別Class,每一台生產出來的車子 =>物件Object
類別提供藍圖能初始化製造物件,利用初始化給物件屬性及定義
創建物件個屬性
class Car:
def __init__(self, make, model, year, color):
#初始化
self.make = make
self.modle = modle
self.year = year
self.color = color
car1 = Car("Toyota", "Altis", 2021, "blue")
Car2 = Car("Ford", "Kuga", 2020, "black")
print(car1, make)
print(car1, modle)
print(car1, year)
print(car1, color)
Toyota
Altis
2021
blue
創建物件功能函式
class Car:
def __init__(self, make, model, year, color):
#初始化
self.make = make
self.modle = modle
self.year = year
self.color = color
def drive(slef):
print(self.modle + "正在行駛")
def stop(self):
print(self.modle + "已停止")
car1 = Car("Toyota", "Altis", 2021, "blue")
Car2 = Car("Ford", "Kuga", 2020, "black")
car1 drive()
car2 drive()
car1 stop()
Altis正在行駛
Kuga正在行駛
Altis已停止
類別變數
class Car:
wheels = 4
#因所有類別都為此變數,可直接宣告
def __init__(self, make, model, year, color):
#初始化
self.make = make
self.modle = modle
self.year = year
self.color = color
Car1 = Car("Ford", "Focus", 2023, "gray")
print(car1, wheels)
#機車
Car2 = Car("Gogoro", "CrossOver", 2024, "gray")
print(car2.models)
car2.wheels = 2
print(car2.wheels)
4
CrossOver
2