一、創(chuàng)建類和實例化對象
1. 怎么創(chuàng)建類
使用關鍵字class ,并且類名要大寫;緊接著更上的是構造函數(shù)__init__只要實例化這個類就會自動運行。構造函數(shù)后面是自定義函數(shù)。
class Person:
def __init__(self,name):
self.name = name
def say_hello(self):
print("打招呼","大家好,我叫:"+self.name)
除了以上這種創(chuàng)建類的方法外,通常我們還見到以下創(chuàng)建類的方法:
class Person(object):
def __init__(self,name):
self.name = name
def say_hello(self):
print("打招呼","大家好,我叫:"+self.name)
小括號內(nèi)加上object,這在我們后面介紹類的繼承的時候會具體講解,這里的小括號表示繼承object類。Python中所有的類都繼承這個叫object的根類,這個object也可以省略,表示默認繼承object類。
class Person:
"""
Person是描述人的基本類:包含了姓名性別、出生日期、手機、郵箱、地址
"""
def __init__(self,name,gender,birthday,mobile,email,address):
"""
構造函數(shù):用來初始化類的靜態(tài)特征。在實例化的時候自動運行
:param name: 姓名
"""
self.name = name
self.gender = gender
self.birthday = birthday
self.mobile = mobile
self.email = email
self.address = address
def say_hello(self):
"""
打招呼的方法,類的動態(tài)特征
:return:
"""
print("打招呼","大家好,我叫:"+self.name)
if __name__ == "__main__":
alice = Person("Alice","女","1998-10-22","13878345893","1232987@qq.com","北京市朝陽區(qū)")
# 訪問靜態(tài)屬性:對象名.靜態(tài)屬性名
print(alice.mobile)
# 訪問動態(tài)屬性:對象名.動態(tài)屬性名()
alice.say_hello()
2. 讀取類的信息
(1)訪問類的名稱:類名.__name__
(2)訪問類的描述信息:類名.__doc__
(3)訪問類的方法的描述信息:類名.方法名.__doc__
(4)訪問類的字典屬性:類名.__dict__
(5)訪問實例對應的類:類名.__class__
3. 總結(jié):關于類和對象
類:把一類事物具有對象的靜態(tài)特征和動態(tài)特征的抽象表達;
對象:是特征與技能的結(jié)合體,其中特征和技能分別對應對象的數(shù)據(jù)屬性和方法屬性。
二、面向?qū)ο蟮乃季S開發(fā)簡單計算器
我們先用面向過程的思維開發(fā)一款簡單的計算器:
if __name__ == "__main__":
num01 = int(input("請輸入第一個整數(shù):"))
action = input("請選擇要執(zhí)行的操作【加+、減-、乘*、除/、求余%】:")
num02 = int(input("請輸入第一個整數(shù):"))
if action == "+":
print("%d + %d = %d"%(num01,num02,num01+num02))
elif action == "-":
print("%d - %d = %d" % (num01, num02, num01 - num02))
elif action == "*":
print("%d * %d = %d" % (num01, num02, num01 * num02))
elif action == "/":
print("%d / %d = %.2f" % (num01, num02, num01 / num02))
elif action == "%":
print(str(num01)+ "%" +str(num02)+"="+str(num01%num02))
else:
print("您的輸入有誤")
輸出結(jié)果:

雖然代碼很簡潔、但是很難復用; 所以我們轉(zhuǎn)為面向?qū)ο蟮乃季S的開發(fā):
我們建一個calclass.py的類,用于計算器的計算:
class Calculator:
def __init__(self,num01,num02,action=""): # 這里action預設為空值,表示兼容只傳兩個參數(shù)的情況
self.num01 = int(num01)
self.num02 = int(num02)
self.action = action
def get_result(self):
if "+" in self.action:
return self.add()
if "-" in self.action:
return self.sub()
if "*" in self.action:
return self.mul()
if "/" in self.action:
return self.div()
if "%" in self.action:
return self.yu()
def add(self):
return self.num01 + self.num02
def sub(self):
return self.num01 - self.num02
def mul(self):
return self.num01 * self.num02
def div(self):
return self.num01 / self.num02
def yu(self):
return self.num01 % self.num02
def print_result(self,action:str,result):
print(str(self.num01)+" "+action+" "+str(self.num02)+" = "+str(result))
然后再創(chuàng)建一個計算器的布局文件:
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
import calclass
# 整個窗體的GUI就是一個類
class Calculator:
def __init__(self):
self.frame = Tk()
self.frame.title("計算器")
self.frame.geometry("560x120+300+250")
self.frame.resizable(0,0)
# self.frame["bg"] = "darkgray"
self.style01 = Style()
self.style01.configure("TButton",font=("微軟雅黑",14,"bold"))
# 添加一個文本輸入框
self.var_num01 = StringVar()
self.Entry_num01 = Entry(self.frame,textvariable = self.var_num01,font = ("微軟雅黑",14,"bold"),width = 10)
self.Entry_num01.place(x=10,y=40)
# 添加一個下拉框的運算符
self.var_action = StringVar()
self.ComboBox_action = Combobox(self.frame,font = ("微軟雅黑",14,"bold"),textvariable = self.var_action,width = 6)
self.ComboBox_action["values"] = ["加【+】","減【-】","乘【*】","除【/】","余【%】"]
self.ComboBox_action["state"] = "readonly"
self.ComboBox_action.current(0)
# self.ComboBox_action.bind("<<ComboboxSelected>>",self.sel_operator)
self.ComboBox_action.place(x = 120,y = 40)
# 添加一個文本輸入框 --num02
self.var_num02 = StringVar()
self.Entry_num02 = Entry(self.frame, textvariable = self.var_num02,font=("微軟雅黑", 14, "bold"), width=10)
self.Entry_num02.place(x=210, y=40)
# 添加一個Label標簽 --Label
self.Label_result = Label(self.frame,text = "=",font=("微軟雅黑", 14, "bold"))
self.Label_result.place(x = 320,y = 43)
# 添加一個文本輸入框 --result
self.var_result = StringVar()
self.Entry_result = Entry(self.frame, textvariable = self.var_result,state=DISABLED,font=("微軟雅黑", 14, "bold"), width=10)
self.Entry_result.place(x=340, y=40)
# 顯示計算按鈕
self.Button_cal = Button(self.frame,style = "TButton",text = "計算",command = self.number_cal)
self.Button_cal.place(x=450,y=43)
def number_cal(self):
num01 = self.var_num01.get()
num02 = self.var_num02.get()
action = self.var_action.get()
my_cal = calclass.Calculator(num01,num02,action)
self.var_result.set(my_cal.get_result())
def show(self):
self.frame.mainloop()
if __name__ == '__main__':
my_calculator = Calculator()
my_calculator.show()
效果演示:

雖然在這里,使用面向?qū)ο箝_發(fā)的方式寫的代碼看上去要比直接面向過程的方式要復雜一些,但是使用面向?qū)ο筮M行封裝后面的代碼可以多次復用,面向?qū)ο蟮膬?yōu)勢就體現(xiàn)出來了。
三、類和對象的內(nèi)存分配
對象(實例)本身只有數(shù)據(jù)(靜態(tài))屬性,但是Python的class機制會將函數(shù)(動態(tài))綁定到對象上,稱為對象的方法,或者叫綁定方法。
四、self關鍵字
在Python面向?qū)ο蟮拇a中,self關鍵字出現(xiàn)的頻率非常高,它究竟代表了什么意思呢?
self 本質(zhì)就是一個指針,指向當前對象所占內(nèi)存空間的一個指針,同C#、Java中的this關鍵字
五、實現(xiàn)構造函數(shù)的“重載”
重載的含義是:方法名相同,參數(shù)個數(shù)不同;
java、C#都具備重載的特性,但是Python沒有,那么在構造對象的時候,參數(shù)的個數(shù)不足構造函數(shù)的參數(shù)個數(shù)該怎么辦呢?
解決這個問題的辦法有兩個:
1.給類的構造函數(shù)設置默認值
通常設為""空,表明在構造對象時,如果提供了參數(shù)就使用提供的參數(shù),如果沒有提供參數(shù)就使用默認的空值,這樣構造對象時就不會報錯。
class Person:
def __init__(self,name="",gender="",age="",mobile="",email="",address=""):
self.name = name
self.gender = gender
self.age = age
self.mobile = mobile
self.email = email
self.address = address
def say_hello(self):
print("大家好,我是"+self.name+"!希望大家支持我!")
if __name__ == "__main__":
# ====== alice ========
alice = Person("Alice","男","23","13771789878","12344@qq.com","北京市海淀區(qū)")
print(alice.address)
alice.say_hello()
# ====== bob =========
bob = Person("Bob","男")
print(bob.address)
bob.say_hello()
2.構造函數(shù)使用不定長參數(shù)
不定長參數(shù)使用*開頭,一般設置為*args,在構造函數(shù)的靜態(tài)屬性賦值的時候設置一個初始值;
class Person:
def __init__(self,*args):
self.name = ""
self.gender = ""
self.age = ""
self.mobile = ""
self.email = ""
self.address = ""
if len(args) == 0:
return
elif len(args) == 1:
self.name = args[0]
elif len(args) == 2:
self.name = args[0]
self.gender = args[1]
elif len(args) == 3:
self.name = args[0]
self.gender = args[1]
self.age = args[2]
elif len(args) == 4:
self.name = args[0]
self.gender = args[1]
self.age = args[2]
self.mobile = args[3]
elif len(args) == 5:
self.name = args[0]
self.gender = args[1]
self.age = args[2]
self.mobile = args[3]
self.email = args[4]
elif len(args) == 6:
self.name = args[0]
self.gender = args[1]
self.age = args[2]
self.mobile = args[3]
self.email = args[4]
self.address = args[5]
def say_hello(self):
print("大家好,我是"+self.name+"!希望大家支持我!")
if __name__ == "__main__":
# ====== alice ========
alice = Person("Alice","男","23","13771789878","12344@qq.com","北京市海淀區(qū)")
print(alice.address)
alice.say_hello()
# ====== bob =========
bob = Person("Bob","男")
print(bob.address)
bob.say_hello()
# ===== peter ========
peter = Person("peter")
peter.say_hello()