issubclass在python中的意思_python基础之类的isinstance与issubclass、反射
一 isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls)檢查是否obj是否是類 cls 的對象
class Foo:
pass
obj = Foo()
print(isinstance(obj,Foo))
issubclass(sub, super)檢查sub類是否是 super 類的派生類
class Foo:
pass
class Bar(Foo):
pass
print(issubclass(Bar,Foo))
二 反射
1、什么是反射
主要是指程序可以訪問、檢測和修改它本身狀態(tài)或行為的一種能力(自省)。
2、python面向?qū)ο笾械姆瓷?#xff1a;通過字符串的形式操作對象相關(guān)的屬性。python中的一切事物都是對象(都可以使用反射)
基于對象級別的反射
基于類級別的反射
基于模塊級別的反射
四個可以實現(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
#檢測是否含有某屬性
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 #基于對象
print(hasattr(People,'country')) #People.country #基于類
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','這個屬性確實不存在'))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'))
四大金剛
#反射當前模塊的屬性
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)
大力丸
模塊補充:
__name__可以區(qū)別文件的用途:
一種用途是直接運行文件,這叫把文件當成腳本運行。
一種用途是不運行文件,在另一個文件中導入這個模塊。
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()
實例一
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()
使用反射來實現(xiàn):實例一
好處一:實現(xiàn)可插拔機制
反射的好處就是,可以事先定義好接口,接口只有在被完成后才會真正執(zhí)行,這實現(xiàn)了即插即用,這其實是一種‘后期綁定’,什么意思?即你可以事先把主要的邏輯寫好(只定義接口),然后后期再去實現(xiàn)接口的功能
模擬FTP功能:
classFtpClient:'ftp客戶端,但是還么有實現(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
好處二:動態(tài)導入模塊(基于反射當前模塊)
#m=input("請輸入你要導入的模塊:")
#m1=__import__(m)#print(m1)#print(m1.time())
#推薦使用方法
importimportlib
t=importlib.import_module('time')print(t.time())
通過字符串導入模塊
總結(jié)
以上是生活随笔為你收集整理的issubclass在python中的意思_python基础之类的isinstance与issubclass、反射的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java单元格合并多列_ElementU
- 下一篇: c语言课设报告时钟vc环境,C语言课程设