issubclass在python中的意思_python基础之类的isinstance与issubclass、反射
一 isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls)檢查是否obj是否是類(lèi) cls 的對(duì)象
class Foo:
pass
obj = Foo()
print(isinstance(obj,Foo))
issubclass(sub, super)檢查sub類(lèi)是否是 super 類(lèi)的派生類(lèi)
class Foo:
pass
class Bar(Foo):
pass
print(issubclass(Bar,Foo))
二 反射
1、什么是反射
主要是指程序可以訪問(wèn)、檢測(cè)和修改它本身狀態(tài)或行為的一種能力(自省)。
2、python面向?qū)ο笾械姆瓷?#xff1a;通過(guò)字符串的形式操作對(duì)象相關(guān)的屬性。python中的一切事物都是對(duì)象(都可以使用反射)
基于對(duì)象級(jí)別的反射
基于類(lèi)級(jí)別的反射
基于模塊級(jí)別的反射
四個(gè)可以實(shí)現(xiàn)自省的函數(shù):
def hasattr(*args, **kwargs): #real signature unknown
"""Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError."""
pass
#檢測(cè)是否含有某屬性
hasattr(object,name)
def getattr(object, name, default=None): #known special case of getattr
"""getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case."""
pass
#獲取屬性
getattr(object, name, default=None)
def setattr(x, y, v): #real signature unknown; restored from __doc__
"""Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''"""
pass
#設(shè)置屬性
setattr(x, y, v)
def delattr(x, y): #real signature unknown; restored from __doc__
"""Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''"""
pass
#刪除屬性
delattr(x, y)
使用演示:
classPeople:
country='China'
def __init__(self,name):
self.name=namedefwalk(self):print('%s is walking'%self.name)
p=People('egon')print(People.__dict__)print(p.name)print(p.__dict__)#----------------------
#hasattr
print('name' in p.__dict__)print(hasattr(p,'name'))print(hasattr(p,'name1213'))print(hasattr(p,'country')) #p.country #基于對(duì)象
print(hasattr(People,'country')) #People.country #基于類(lèi)
print(hasattr(People,'__init__')) #People.__init__
#----------------------
#getattr
res=getattr(p,'country') #res=p.country
print(res)
f=getattr(p,'walk') #t=p.walk
print(f)
f1=getattr(People,'walk')print(f1)
f()
f1(p)print(p.xxxxxxx)print(getattr(p,'xxxxxxxx','這個(gè)屬性確實(shí)不存在'))if hasattr(p,'walk'):
func=getattr(p,'walk')
func()print('================>')print('================>')#----------------------
#setattr
p.sex='male'
print(p.sex)print(p.__dict__)
setattr(p,'age',18)print(p.__dict__)print(p.age)print(getattr(p,'age'))
四大金剛
#反射當(dāng)前模塊的屬性
importsys
x=1111
classFoo:pass
defs1():print('s1')defs2():print('s2')#print(__name__)
this_module= sys.modules[__name__]print(this_module)print(hasattr(this_module, 's1'))print(getattr(this_module, 's2'))print(this_module.s2)print(this_module.s1)
大力丸
模塊補(bǔ)充:
__name__可以區(qū)別文件的用途:
一種用途是直接運(yùn)行文件,這叫把文件當(dāng)成腳本運(yùn)行。
一種用途是不運(yùn)行文件,在另一個(gè)文件中導(dǎo)入這個(gè)模塊。
3、反射的用途
importsysdefadd():print('add')defchange():print('change')defsearch():print('search')defdelete():print('delete')
func_dic={'add':add,'change':change,'search':search,'delete':delete
}whileTrue:
cmd=input('>>:').strip()if not cmd:continue
if cmd in func_dic: #hasattr()
func=func_dic.get(cmd) #func=getattr()
func()
實(shí)例一
importsysdefadd():print('add')defchange():print('change')defsearch():print('search')defdelete():print('delete')
this_module=sys.modules[__name__]whileTrue:
cmd=input('>>:').strip()if not cmd:continue
ifhasattr(this_module,cmd):
func=getattr(this_module,cmd)
func()
使用反射來(lái)實(shí)現(xiàn):實(shí)例一
好處一:實(shí)現(xiàn)可插拔機(jī)制
反射的好處就是,可以事先定義好接口,接口只有在被完成后才會(huì)真正執(zhí)行,這實(shí)現(xiàn)了即插即用,這其實(shí)是一種‘后期綁定’,什么意思?即你可以事先把主要的邏輯寫(xiě)好(只定義接口),然后后期再去實(shí)現(xiàn)接口的功能
模擬FTP功能:
classFtpClient:'ftp客戶(hù)端,但是還么有實(shí)現(xiàn)具體的功能'
def __init__(self,addr):print('正在連接服務(wù)器[%s]' %addr)
self.addr=addrdeftest(self):print('test')defget(self):print('get------->')
ftpclient.py
importftpclient#print(ftpclient)#print(ftpclient.FtpClient)#obj=ftpclient.FtpClient('192.168.1.3')
#print(obj)#obj.test()
f1=ftpclient.FtpClient('192.168.1.1')if hasattr(f1,'get'):
func=getattr(f1,'get')
func()else:print('-->不存在此方法')print('其他邏輯')
ftpserver.py
好處二:動(dòng)態(tài)導(dǎo)入模塊(基于反射當(dāng)前模塊)
#m=input("請(qǐng)輸入你要導(dǎo)入的模塊:")
#m1=__import__(m)#print(m1)#print(m1.time())
#推薦使用方法
importimportlib
t=importlib.import_module('time')print(t.time())
通過(guò)字符串導(dǎo)入模塊
總結(jié)
以上是生活随笔為你收集整理的issubclass在python中的意思_python基础之类的isinstance与issubclass、反射的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java单元格合并多列_ElementU
- 下一篇: c语言课设报告时钟vc环境,C语言课程设