對象的做用:存儲一些值,之後方便本身使用python
class File: def read(self): with open(self.xxxxx, mode='r', encoding='utf-8') as f: data = f.read() return data def write(self, content): with open(self.xxxxx, mode='a', encoding='utf-8') as f: f.write(content) # # 實例化了一個File類的對象 obj1 = File() # # 在對象中寫了一個xxxxx = 'test.log' obj1.xxxxx = "test.log" # # 經過對象調用類中的read方法,read方法中的self就是obj。 # # obj1.read() obj1.write('alex') # 實例化了一個File類的對象 obj2 = File() # 在對象中寫了一個xxxxx = 'test.log' obj2.xxxxx = "info.txt" # 經過對象調用類中的read方法,read方法中的self就是obj。 # obj2.read() obj2.write('alex')
封裝的做用:將數據封裝到對象,方便使用面試
class Person: def __init__(self,n,a,g): # 初始化方法(構造方法),給對象的內部作初始化。 self.name = n self.age = a self.gender = g def show(self): temp = "我是%s,年齡:%s,性別:%s " % (self.name, self.age, self.gender,) print(temp) # 類() 實例化對象,自動執行此類中的 __init__方法。 p1 = Person('李兆琪',19,'男') p1.show() p2 = Person('利奇航',19,'男') p2.show()
總結app
# 示例:循環讓用戶輸入:用戶名/密碼/郵箱。 輸入完成後再進行數據打印。 # 之前的寫法: USER_LIST = [] while True: user = input('請輸入用戶名:') pwd = input('請輸入密碼:') email = input('請輸入郵箱:') temp = {'username':user,'password':pwd,'email':email} USER_LIST.append(temp) for item in USER_LIST: temp = "個人名字:%s,密碼:%s,郵箱%s" %(item['username'],item['password'],item['email'],) print(temp) # 面向對象寫法一: class Person: def __init__(self,user,pwd,email): self.username = user self.password = pwd self.email = email USER_LIST = [對象(用戶/密碼/郵箱),對象(用戶/密碼/郵箱),對象(用戶/密碼/郵箱)] while True: user = input('請輸入用戶名:') pwd = input('請輸入密碼:') email = input('請輸入郵箱:') p = Person(user,pwd,email) USER_LIST.append(p) for item in USER_LIST: temp = "個人名字:%s,密碼:%s,郵箱%s" %(item.username,item.password,item.email,) print(temp) # 面向對象寫法二: class Person: def __init__(self,user,pwd,email): self.username = user self.password = pwd self.email = email def info(self): return "個人名字:%s,密碼:%s,郵箱%s" %(item.username,item.password,item.email,) USER_LIST = [對象(用戶/密碼/郵箱),對象(用戶/密碼/郵箱),對象(用戶/密碼/郵箱)] while True: user = input('請輸入用戶名:') pwd = input('請輸入密碼:') email = input('請輸入郵箱:') p = Person(user,pwd,email) USER_LIST.append(p) for item in USER_LIST: msg = item.info() print(msg)
基本內容函數
# 父類(基類) class Base: def f1(self): pass # 子類(派生類) class Foo(Base): def f2(self): pass # 建立了一個子類的對象 obj = Foo() # 執行對象.方法時,優先在本身的類中找,若是沒有就是父類中找 obj.f2() obj.f1() # 建立了一個父類的對象 obj = Base() obj.f1()
總結code
基本內容:多種形態/多種類型,python自己就是多態的對象
def func(arg): # 多種類型,不少事物 arg.send() # 必須具備send方法,呱呱叫
面試題:什麼是鴨子模型?繼承
對於一個函數而言,Python對於參數的類型不會限制,那麼傳入參數時就能夠是各類類型,在函數中若是有例如:arg.send方法,那麼就是對於傳入類型的一個限制(類型必須有send方法),這就是鴨子模型utf-8
相似於上述的函數咱們認爲只要能呱呱叫的就是鴨子(只有有send方法,就是咱們想要的類型)input