類別、物件基礎
# Python 類別與物件基礎
在 Python 中:
- **類別(Class)**:物件的藍圖或設計圖,定義物件具有哪些屬性與方法。
- **物件(Object)**:根據類別建立出來的實際資料。
- **屬性(Attribute)**:物件保存的資料,例如姓名、年齡。
- **方法(Method)**:物件可以執行的功能,通常定義在類別中。
---
## 一、類別的基本定義
使用 `class` 定義類別:
```python
class 類別名稱:
# 屬性與方法
pass
```
例如:
```python
class Person:
pass
```
這樣就建立了一個名為 `Person` 的類別。
---
## 二、初始化函式 `__init__`
`__init__` 是類別的初始化函式,在建立物件時會自動執行,通常用來設定物件的初始屬性。
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
```
說明:
- `self` 代表目前建立的物件本身。
- `name` 和 `age` 是傳入的參數。
- `self.name` 和 `self.age` 是物件的屬性。
---
## 三、物件方法定義
方法是定義在類別中的函式,第一個參數通常必須是 `self`。
```python
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"你好,我是 {self.name}。")
```
呼叫方法時不需要自行傳入 `self`:
```python
person.say_hello()
```
---
# 範例一:建立學生物件
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def show_info(self):
print(f"姓名:{self.name}")
print(f"分數:{self.score}")
def is_pass(self):
return self.score >= 60
# 根據 Student 類別建立物件
student1 = Student("小明", 85)
student2 = Student("小華", 55)
# 使用物件的屬性
print(student1.name) # 小明
print(student1.score) # 85
# 使用物件的方法
student1.show_info()
print(student1.is_pass()) # True
print(student2.is_pass()) # False
```
## 重點
```python
student1 = Student("小明", 85)
```
代表根據 `Student` 類別建立一個物件,並呼叫 `__init__` 設定:
```python
student1.name = "小明"
student1.score = 85
```
---
# 範例二:矩形類別
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# 建立矩形物件
rectangle = Rectangle(10, 5)
# 使用屬性
print("寬度:", rectangle.width)
print("高度:", rectangle.height)
# 使用方法
print("面積:", rectangle.area())
print("周長:", rectangle.perimeter())
```
輸出結果:
```text
寬度: 10
高度: 5
面積: 50
周長: 30
```
方法可以使用物件的屬性進行計算。
---
# 範例三:銀行帳戶
```python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"存入 {amount} 元")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"提領 {amount} 元")
else:
print("餘額不足")
def show_balance(self):
print(f"{self.owner} 的目前餘額:{self.balance} 元")
# 建立帳戶物件
account = BankAccount("小美", 1000)
# 使用方法
account.show_balance()
account.deposit(500)
account.show_balance()
account.withdraw(300)
account.show_balance()
account.withdraw(2000)
```
可能的輸出:
```text
小美 的目前餘額:1000 元
存入 500 元
小美 的目前餘額:1500 元
提領 300 元
小美 的目前餘額:1200 元
餘額不足
```
---
# 四、使用物件屬性與方法
假設有以下類別:
```python
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name}:汪汪!")
```
建立物件:
```python
dog = Dog("小黑")
```
使用屬性:
```python
print(dog.name)
```
使用方法:
```python
dog.bark()
```
也可以修改物件屬性:
```python
dog.name = "小白"
print(dog.name)
dog.bark()
```
---
## 五、基本語法整理
```python
class 類別名稱:
def __init__(self, 參數):
self.屬性 = 參數
def 方法名稱(self):
# 方法內容
pass
物件名稱 = 類別名稱(參數)
物件名稱.屬性
物件名稱.方法名稱()
```
例如:
```python
class Car:
def __init__(self, brand):
self.brand = brand
def drive(self):
print(f"{self.brand} 正在行駛")
car = Car("Toyota")
print(car.brand)
car.drive()
```
其中:
- `class Car`:定義類別。
- `__init__`:初始化物件。
- `self.brand`:物件屬性。
- `drive()`:物件方法。
- `car = Car("Toyota")`:建立物件。
- `car.brand`:存取屬性。
- `car.drive()`:呼叫方法。
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫