# Python 對象和類
> 原文: [https://thepythonguru.com/python-object-and-classes/](https://thepythonguru.com/python-object-and-classes/)
* * *
于 2020 年 1 月 7 日更新
* * *
## 創建對象和類
* * *
Python 是一種面向對象的語言。 在 python 中,所有東西都是對象,即`int`,`str`,`bool`甚至模塊,函數也是對象。
面向對象的編程使用對象來創建程序,這些對象存儲數據和行為。
## 定義類
* * *
python 中的類名以`class`關鍵字開頭,后跟冒號(`:`)。 類通常包含用于存儲數據的數據字段和用于定義行為的方法。 python 中的每個類還包含一個稱為*初始化器*的特殊方法(也稱為構造器),該方法在每次創建新對象時自動被調用。
讓我們來看一個例子。
```py
class Person:
? ? ? ?# constructor or initializer
? ? ? def __init__(self, name):
? ? ? ? ? ? self.name = name # name is data field also commonly known as instance variables
? ? ? # method which returns a string
? ? ?def whoami(self):
? ? ? ? ? ?return "You are " + self.name
```
在這里,我們創建了一個名為`Person`的類,其中包含一個名為`name`和方法`whoami()`的數據字段。
## 什么是`self`?
* * *
python 中的所有方法(包括一些特殊方法,如初始化器)都具有第一個參數`self`。 此參數引用調用該方法的對象。 創建新對象時,會自動將`__init__`方法中的`self`參數設置為引用剛創建的對象。
## 從類創建對象
* * *
```py
p1 = Person('tom') # now we have created a new person object p1
print(p1.whoami())
print(p1.name)
```
**預期輸出**:
```py
You are tom
tom
```
**注意**:
當您調用一個方法時,您無需將任何內容傳遞給`self`參數,python 就會在后臺自動為您完成此操作。
您也可以更改`name`數據字段。
```py
p1.name = 'jerry'
print(p1.name)
```
**預期輸出**:
```py
jerry
```
盡管在類之外授予對您的數據字段的訪問權是一種不好的做法。 接下來,我們將討論如何防止這種情況。
## 隱藏數據字段
* * *
要隱藏數據字段,您需要定義私有數據字段。 在 python 中,您可以使用兩個前劃線來創建私有數據字段。 您還可以使用兩個下劃線定義私有方法。
讓我們看一個例子
```py
class BankAccount:
? ? ?# constructor or initializer
? ? def __init__(self, name, money):
? ? ? ? ?self.__name = name
? ? ? ? ?self.__balance = money ? # __balance is private now, so it is only accessible inside the class
? ? def deposit(self, money):
? ? ? ? ?self.__balance += money
? ? def withdraw(self, money):
? ? ? ? ?if self.__balance > money :
? ? ? ? ? ? ?self.__balance -= money
? ? ? ? ? ? ?return money
? ? ? ? ?else:
? ? ? ? ? ? ?return "Insufficient funds"
? ? def checkbalance(self):
? ? ? ? ?return self.__balance
b1 = BankAccount('tim', 400)
print(b1.withdraw(500))
b1.deposit(500)
print(b1.checkbalance())
print(b1.withdraw(800))
print(b1.checkbalance())
```
**預期輸出**:
```py
Insufficient funds
900
800
100
```
讓我們嘗試訪問類外部的`__balance`數據字段。
```py
print(b1.__balance)
```
**預期輸出**:
```py
AttributeError: 'BankAccount' object has no attribute '__balance'
```
如您所見,現在在類外部無法訪問`__balance`字段。
在下一章中,我們將學習[運算符重載](/python-operator-overloading/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象