亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区
Chinaunix
標(biāo)題:
一個(gè)得到類命名的方法
[打印本頁]
作者:
jeppeter
時(shí)間:
2013-04-26 13:31
標(biāo)題:
一個(gè)得到類命名的方法
想得到一個(gè)類全名,但找了很多的方法,都沒有辦法直接得到,如
class AUnit(object):
def GetMsg(self):
return clsname.GetCallerClassName(1)
class AUnit2(object):
def GetMsg(self):
return clsname.GetCallerClassName(1)
class AUnit3(object):
def GetMsg(self):
return clsname.GetCallerClassName(1)
復(fù)制代碼
在AUnit.GetMsg()函數(shù)調(diào)用,得到這個(gè)函數(shù)的調(diào)用類的時(shí)候,要返回的是
__main__.AUnit
復(fù)制代碼
當(dāng)然這里假設(shè)是在__main__的模塊內(nèi)調(diào)用
如果是AUnit.AUnit2.GetMsg()調(diào)用,得到的是
__main__.AUnit.AUnit2
復(fù)制代碼
依此類推。
只好自己動(dòng)手寫一個(gè)
#! python
import inspect
import types
import logging
def FuncMethodSearh(obj):
if inspect.ismethod(obj):
return True
if inspect.isfunction(obj):
return True
if inspect.isclass(obj):
return True
return False
def __IsCodeInClass(clsobj,codeobj):
mns = inspect.getmembers(clsobj,predicate=FuncMethodSearh)
ret = 0
for m in mns:
#logging.info('%s %s'%(repr(m[1]),repr(codeobj)))
if type(m[1]) is types.MethodType or type(m[1]) is types.FunctionType or\
type(m[1]) is types.GeneratorType:
fobj = m[1].func_code
if fobj.co_name == codeobj.co_name and \
fobj.co_firstlineno == codeobj.co_firstlineno:
ret = 1
break
return ret
def __GetCodeObjClass(clsobj,codeobj,calllevel=0):
if calllevel > 300:
raise
ret = __IsCodeInClass(clsobj,codeobj)
if ret > 0:
return clsobj.__name__
mns = inspect.getmembers(clsobj,predicate=inspect.isclass)
for m in mns:
# we do not recursive for the two types
if m[0] != '__class__' and m[0] != '__base__':
#logging.info('%s %s'%(repr(m[1]),repr(codeobj)))
n = __GetCodeObjClass(m[1],codeobj,calllevel + 1)
if n:
return clsobj.__name__+'.'+n
return None
def GetCallerClassFullName(modobj,codeobj):
'''
@modobj : module object area to search for code object
@codeobj : code object will find its class belong to
@return : it codeobj can not detect the name return module name
if codeobj is the function not belong to any of the class
return the module name
if codeobj is the method or function of class ,return whole class name including module name
'''
mns = inspect.getmembers(modobj,predicate=FuncMethodSearh)
ret = 0
for m in mns:
if type(m[1]) is types.MethodType or type(m[1]) is types.FunctionType or\
type(m[1]) is types.GeneratorType:
fobj = m[1].func_code
if fobj.co_name == codeobj.co_name and \
fobj.co_firstlineno == codeobj.co_firstlineno:
ret = 1
break
if ret > 0:
return modobj.__name__
mns = inspect.getmembers(modobj,predicate=inspect.isclass)
for m in mns:
n = __GetCodeObjClass(m[1],codeobj)
if n:
return modobj.__name__ +'.'+n
return modobj.__name__
def GetCallerClassName(level=2):
mn = ''
stks = inspect.stack()
if len(stks) > level:
frm = stks[level]
mm = inspect.getmodule(frm[0])
fc = frm[0].f_code
mn = GetCallerClassFullName(mm,fc)
return mn
復(fù)制代碼
大家可以測(cè)試。
歡迎光臨 Chinaunix (http://72891.cn/)
Powered by Discuz! X3.2