今日內容
- 面向物件基本用法
- 好處和應用場景
- 面向物件的三大特性
內容詳細
1.面向物件基本格式
# ###### 定義類 ######
class 類名:
def 方法名(self,name):
print(name)
return 123
def 方法名(self,name):
print(name)
return 123
def 方法名(self,name):
print(name)
return 123
# ###### 呼叫類中的方法 ######
# 1.創建該類的物件
obj = 類名()
# 2.通過物件呼叫方法
result = obj.方法名('alex')
print(result)
應用場景:遇到很多函式,需要給函式進行歸類和劃分, 【封裝】
練習題:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Db:
def db_read(self):
pass
def db_write(self):
pass
def db_delete(self):
pass
def db_update(self):
pass
class File:
def file_read(self):
pass
def file_write(self):
pass
def file_delete(self):
pass
def file_update(self):
pass
class Redis:
def redis_read(self):
pass
def redis_write(self):
pass
def redis_delete(self):
pass
def redis_update(self):
pass
2.物件的作用
存盤一些值,以后方便自己使用,
class File:
def read(self):
with open(self.xxxxx, mode='r', encoding='utf-8') as f:
data = https://www.cnblogs.com/cuiyongchao007/p/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 show(self):
temp = "我是%s,年齡:%s,性別:%s " %(self.name,self.age,self.gender,)
print(temp)
p1 = Person()
p1.name = '李邵奇'
p1.age = 19
p1.gender = '男'
p1.show()
p2 = Person()
p2.name = '利奇航'
p2.age = 19
p2.gender = '男'
p2.show()
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()
總結:將資料封裝到物件,方便使用,
總結
"""
如果寫代碼時,函式比較多比較亂,
1. 可以將函式歸類并放到同一個類中,
2. 函式如果有一個反復使用的公共值,則可以放到物件中,
"""
class File:
def __init__(self,path):
self.file_path = path
def read(self):
print(self.file_path)
def write(self,content):
print(self.file_path)
def delete(self):
print(self.file_path)
def update(self):
print(self.file_path)
p1 = File('log.txt')
p1.read()
p2 = File('xxxxxx.txt')
p2.read()
# 1. 回圈讓用戶輸入:用戶名/密碼/郵箱, 輸入完成后再進行資料列印,
# ########## 以前的寫法
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)
3.游戲開發
class Police:
def __init__(self,name)
self.name = name
self.hp = 10000
def tax(self):
msg = "%s收了個稅," %(self.name,)
print(msg)
def fight(self):
msg = "%s去戰了個斗," %(self.name,)
lsq = Police('李邵奇')
zzh = Police('渣渣會')
tyg = Police('堂有光')
class Bandit:
def __init__(self,nickname)
self.nickname = nickname
self.hp = 1000
def murder(self,name):
msg = "%s去謀殺了%s" %(self.nickname, name,)
lcj = Bandit('二蛋')
lp = Bandit('二狗')
zsd = Bandit('狗蛋')
# 1. 二狗去謀殺渣渣會,二狗生命值-100; 渣渣會生命值減5000
lp.murder(zzh.name)
lp.hp = lp.hp - 100
zzh.hp = zzh.hp - 5000
# ...
class Police:
def __init__(self,name)
self.name = name
self.hp = 10000
def dao(self,other):
msg = "%s個了%s一刀," %(self.name,other.nickname)
self.hp = self.hp - 10
other.hp = other.hp - 50
print(msg)
def qiang(self):
msg = "%s去戰了個斗," %(self.name,)
def quan(self,other):
msg = "%s個了%s一全," %(self.name,other.nickname)
self.hp = self.hp - 2
other.hp = other.hp - 10
print(msg)
class Bandit:
def __init__(self,nickname)
self.nickname = nickname
self.hp = 1000
def qiang(self,other):
msg = "%s個了%s一全," %(self.nickname,other.name)
self.hp -= 20
other.hp -= 500
lcj = Bandit('二蛋')
lsq = Police('李邵奇')
lsq.dao(lcj)
lsq.quan(lcj)
lcj.qiang(lsq)
4.繼承
# 父類(基類)
class Base:
def f1(self):
pass
# 子類(派生類)
class Foo(Base):
def f2(self):
pass
# 創建了一個字類的物件
obj = Foo()
# 執行物件.方法時,優先在自己的類中找,如果沒有就是父類中找,
obj.f2()
obj.f1()
# 創建了一個父類的物件
obj = Base()
obj.f1()
問題:什么時候才能用到繼承?多個類中如果有公共的方法,可以放到基類中避免重復撰寫,
class Base:
def f1(self):
pass
class Foo(Base):
def f2(self):
pass
class Bar(Base):
def f3(self):
pass
obj1 = Foo()
obj2 = Bar()
繼承關系中的查找方法的順序:
# 示例一
class Base:
def f1(self):
print('base.f1')
class Foo(Base):
def f2(self):
print('foo.f2')
obj = Foo()
obj.f1()
obj.f2()
# 示例二
class Base:
def f1(self):
print('base.f1')
class Foo(Base):
def f2(self):
self.f1()
print('foo.f2')
obj = Foo()
obj.f2()
# 示例三
class Base:
def f1(self):
print('base.f1')
class Foo(Base):
def f2(self):
self.f1()
print('foo.f2')
def f1(self):
print('foo.f1')
obj = Foo()
obj.f2()
# 示例四
class Base:
def f1(self):
self.f2()
print('base.f1')
def f2(self):
print('base.f2')
class Foo(Base):
def f2(self):
print('foo.f2')
obj = Foo()
obj.f1()
# 示例五
class TCPServer:
pass
class ThreadingMixIn:
pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass
# 示例六
class BaseServer:
def serve_forever(self, poll_interval=0.5):
self._handle_request_noblock()
def _handle_request_noblock(self):
self.process_request(request, client_address)
def process_request(self, request, client_address):
pass
class TCPServer(BaseServer):
pass
class ThreadingMixIn:
def process_request(self, request, client_address):
pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass
obj = ThreadingTCPServer()
obj.serve_forever()
注意事項:
- self 到底是誰?
- self 是哪個類創建的,就從此類開始找,自己沒有就找父類,
5.多型(多種形態/多種型別)鴨子模型
# Python
def func(arg):
v = arg[-1] # arg.append(9)
print(v)
# java
def func(str arg):
v = arg[-1]
print(v)
面試題:什么是鴨子模型,
對于一個函式而言,Python對于引數的型別不會限制,那么傳入引數時就可以是各種型別,在函式中如果有例如:arg.send方法,那么就是對于傳入型別的一個限制(型別必須有send方法),
這就是鴨子模型,類似于上述的函式我們認為只要能呱呱叫的就是鴨子(只有有send方法,就是我們要想的型別)
總結
-
面向物件的三大特性:封裝/繼承/多型
-
封裝
class File: def read(self): pass def write(self): passclass Person: def __init__(sef,name,age): self.name = name self.age = age p = Person('alex',19) -
繼承
class Base: pass class Foo(Base): pass- 多繼承
- self到底是誰?
- self是由于那個類創建,則找方法時候就從他開始找,
-
多型
def func(arg): # 多種型別,很多事物 arg.send() # 必須具有send方法,呱呱叫
-
-
格式和關鍵詞
class 類: def __init__(self,x): self.x = x def 方法(self,name): print(self.x, name) # 實體化一個類的物件 v1 = 類(666) v2.方法('alex')三個詞:
- 類
- 物件
- 方法
-
什么時候用面向物件?
- 函式(業務功能)比較多,可以使用面向物件來進行歸類,
- 想要做資料封裝(創建字典存盤資料時,面向物件),
- 游戲示例:創建一些角色并且根據角色需要再創建人物,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/205836.html
標籤:Python
