
python進(jìn)階_淺談面向?qū)ο筮M(jìn)階
學(xué)了面向?qū)ο笕筇匦岳^承,多態(tài),封裝。今天我們看看面向?qū)ο蟮囊恍┻M(jìn)階內(nèi)容,反射和一些類的內(nèi)置函數(shù)。
一、isinstance和issubclass
class Foo:
pass
class Son(Foo):
pass
s = Son()
#判斷一個對象是不是這個類的對象,傳兩個參數(shù)(對象,類)
print(isinstance(s,Son))
print(isinstance(s,Foo))
#type更精準(zhǔn)
print(type(s) is Son)
print(type(s) is Foo)
#判斷一個類是不是另一類的子類,傳兩個參數(shù)(子類,父類)
print(issubclass(Son,Foo))
print(issubclass(Son,object))
print(issubclass(Foo,object))
print(issubclass(int,object))
二、反射
反射的概念是由Smith在1982年首次提出的,主要是指程序可以訪問、檢測和修改它本身狀態(tài)或行為的一種能力(自省)。這一概念的提出很快引發(fā)了計算機(jī)科學(xué)領(lǐng)域關(guān)于應(yīng)用反射性的研究。它首先被程序語言的設(shè)計領(lǐng)域所采用,并在Lisp和面向?qū)ο蠓矫嫒〉昧顺煽儭?
python面向?qū)ο笾械姆瓷洌和ㄟ^字符串的形式操作對象相關(guān)的屬性。python中的一切事物都是對象(都可以使用反射)
四個可以實現(xiàn)反射的函數(shù):hasattr,getattr,setattr,delattr
下列方法適用于類和對象(一切皆對象,類本身也是一個對象)
class Foo:
def __init__(self):
self.name = 'egon'
self.age = 73
def func(self):
print(123)
egg = Foo()
#常用:
#hasattr
#getattr
# print(hasattr(egg,'name'))
print(getattr(egg,'name'))
if hasattr(egg,'func'): #返回bool
Foo_func = getattr(egg,'func') #如果存在這個方法或者屬性,就返回屬性值或者方法的內(nèi)存地址
#如果不存在,報錯,因此要配合hasattr使用
Foo_func()
#不常用:
#setattr
# setattr(egg,'sex','屬性值')
# print(egg.sex)
# def show_name(self):
# print(self.name + ' sb')
# setattr(egg,'sh_name',show_name)
# egg.sh_name(egg)
# show_name(egg)
# egg.sh_name()
#delattr
# delattr(egg,'name')
# print(egg.name)
# print(egg.name)
# egg.func()
# print(egg.__dict__)
#反射
#可以用字符串的方式去訪問對象的屬性、調(diào)用對象的方法
反射舉例1
class Foo:
f = 123 #類變量
@classmethod
def class_method_demo(cls):
print('class_method_demo')
@staticmethod
def static_method_demo():
print('static_method_demo')
# if hasattr(Foo,'f'):
# print(getattr(Foo,'f'))
print(hasattr(Foo,'class_method_demo'))
method = getattr(Foo,'class_method_demo')
method()
print(hasattr(Foo,'static_method_demo'))
method2 = getattr(Foo,'static_method_demo')
method2()
#類也是對象
反射舉例2
import my_module
# print(hasattr(my_module,'test'))
# # func_test = getattr(my_module,'test')
# # func_test()
# getattr(my_module,'test')()
#import其他模塊應(yīng)用反射
from my_module import test
def demo1():
print('demo1')
import sys
print(__name__) #'__main__'
print(sys.modules)
#'__main__': <module '__main__' from 'D:/Python代碼文件存放目錄/S6/day26/6反射3.py'>
module_obj =sys.modules[__name__] #sys.modules['__main__']
# module_obj : <module '__main__' from 'D:/Python代碼文件存放目錄/S6/day26/6反射3.py'>
print(module_obj)
print(hasattr(module_obj,'demo1'))
getattr(module_obj,'demo1')()
#在本模塊中應(yīng)用反射
反射舉例3
#對象
#類
#模塊 : 本模塊和導(dǎo)入的模塊
def register():
print('register')
def login():
pass
def show_shoppinglst():
pass
#
print('注冊,登錄')
ret = input('歡迎,請輸入您要做的操作: ')
import sys
print(sys.modules)
# my_module = sys.modules[__name__]
# if hasattr(my_module,ret):
# getattr(my_module,ret)()
if ret == '注冊':
register()
elif ret == '登錄':
login()
elif ret == 'shopping':
show_shoppinglst()
反射舉例4
def test():
print('test')
三、類的內(nèi)置函數(shù)
1、__str__和__repr__
class Foo:
def __init__(self,name):
self.name = name
def __str__(self):
return '%s obj info in str'%self.name
def __repr__(self):
return 'obj info in repr'
f = Foo('egon')
# print(f)
print('%s'%f)
print('%r'%f)
print(repr(f)) # f.__repr__()
print(str(f))
#當(dāng)打印一個對象的時候,如果實現(xiàn)了str,打印中的返回值
#當(dāng)str沒有被實現(xiàn)的時候,就會調(diào)用repr方法
#但是當(dāng)你用字符串格式化的時候 %s和%r會分別去調(diào)用__str__和__repr__
#不管是在字符串格式化的時候還是在打印對象的時候,repr方法都可以作為str方法的替補(bǔ)
#但反之不行
#用于友好的表示對象。如果str和repr方法你只能實現(xiàn)一個:先實現(xiàn)repr
2、__del__
class Foo:
def __del__(self):
print('執(zhí)行我啦')
f = Foo()
print(123)
print(123)
print(123)
#析構(gòu)方法,當(dāng)對象在內(nèi)存中被釋放時,自動觸發(fā)執(zhí)行。
#注:此方法一般無須定義,因為Python是一門高級語言,程序員在使用時無需關(guān)心內(nèi)存的分配和釋放,因為此工作都是交給Python解釋器來執(zhí)行,所以,析構(gòu)函數(shù)的調(diào)用是由解釋器在進(jìn)行垃圾回收時自動觸發(fā)執(zhí)行的。
3、item系列
__getitem__\__setitem__\__delitem__
class Foo:
def __init__(self):
self.name = 'egon'
self.age = 73
def __getitem__(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
# print(key,value)
self.__dict__[key] = value
def __delitem__(self, key):
del self.__dict__[key]
f = Foo()
print(f['name'])
print(f['age'])
f['name'] = 'alex'
# del f['name']
print(f.name)
f1 = Foo()
print(f == f1)
4、__new__
# class A:
# def __init__(self): #有一個方法在幫你創(chuàng)造self
# print('in init function')
# self.x = 1
#
# def __new__(cls, *args, **kwargs):
# print('in new function')
# return object.__new__(A, *args, **kwargs)
# a = A()
# b = A()
# c = A()
# d = A()
# print(a,b,c,d)
#單例模式
class Singleton:
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args, **kw)
return cls._instance
one = Singleton()
two = Singleton()
three = Singleton()
go = Singleton()
print(one,two)
one.name = 'alex'
print(two.name)
5、__call__
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = Foo() # 執(zhí)行 __init__
obj() # 執(zhí)行 __call__
Foo()() # 執(zhí)行 __init__和執(zhí)行 __call__
#構(gòu)造方法的執(zhí)行是由創(chuàng)建對象觸發(fā)的,即:對象 = 類名() ;而對于 __call__ 方法的執(zhí)行是由對象后加括號觸發(fā)的,即:對象() 或者 類()()
6、__len__,__hash__
class Foo:
def __len__(self):
return len(self.__dict__)
def __hash__(self):
print('my hash func')
return hash(self.name)
f = Foo()
print(len(f))
f.name = 'egon'
print(len(f))
print(hash(f))
7、__eq__
class A:
def __init__(self):
self.a = 1
self.b = 2
def __eq__(self,obj):
if self.a == obj.a and self.b == obj.b:
return True
a = A()
b = A()
print(a == b)
#__eq__控制著==的結(jié)果
8、內(nèi)置函數(shù)實例
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = ['紅心','方板','梅花','黑桃']
def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))
紙牌游戲
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = ['紅心','方板','梅花','黑桃']
def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
def __setitem__(self, key, value):
self._cards[key] = value
deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))
from random import shuffle
shuffle(deck)
print(deck[:5])
紙牌游戲2
class Person:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def __hash__(self):
return hash(self.name+self.sex)
def __eq__(self, other):
if self.name == other.name and other.sex == other.sex:return True
p_lst = []
for i in range(84):
p_lst.append(Person('egon',i,'male'))
print(p_lst)
print(set(p_lst))
#只要姓名和年齡相同就默認(rèn)為一人去重
去重
以上這篇python進(jìn)階_淺談面向?qū)ο筮M(jìn)階就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點(diǎn)數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點(diǎn)數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10