Python类浏览器支持
Python库中的pyclbr模块提取有关Python模块中定义的函数,类和方法的信息。该信息是从Python源代码中提取的,而不是通过导入模块来提取的。
该模块定义readmodule()函数,该函数将字典映射模块级别的类名称返回到类描述符。该函数将模块名称作为参数。它可能是包中模块的名称。在这种情况下,路径是sys.path之前的目录路径序列,用于定位模块源代码。
以下代码使用readmodule()函数来解析Python库的套接字模块中的类和方法。
import pyclbr
mod = pyclbr.readmodule("socket")
def show(c):
s = "class " + c.name
print (s + ":")
methods = c.methods.items()
for method, lineno in methods:
print (" def " + method)
print()
for k, v in mod.items():
show(v)class IntEnum: class IntFlag: def _missing_ def _create_pseudo_member_ def __or__ def __and__ def __xor__ def __invert__ class _GiveupOnSendfile: class socket: def __init__ def __enter__ def __exit__ def __repr__ def __getstate__ def dup def accept def makefile def _sendfile_use_sendfile def _sendfile_use_send def _check_sendfile_params def sendfile def _decref_socketios def _real_close def close def detach def family def type def get_inheritable def set_inheritable class SocketIO: def __init__ def readinto def write def readable def writable def seekable def fileno def name def mode def close
pyclbr模块还定义了readmodule_ex()函数,该函数返回一个字典,该字典包含模块中定义的每个函数和类的函数或类描述符。返回的字典将模块级函数和类名称映射到其描述符。嵌套对象被输入到其父级的子级字典中。
>>> x = pyclbr.readmodule_ex('socket')
>>> for k,v in x.items():
print (k,v)
IntEnum <pyclbr.Class object at 0x000002095D7D0048>
IntFlag <pyclbr.Class object at 0x000002095D7D04E0>
_intenum_converter <pyclbr.Function object at 0x000002095D82F940>
_GiveupOnSendfile <pyclbr.Class object at 0x000002095D822898>
socket <pyclbr.Class object at 0x000002095D8227B8>
fromfd <pyclbr.Function object at 0x000002095D8340B8>
fromshare <pyclbr.Function object at 0x000002095D82FEF0>
socketpair <pyclbr.Function object at 0x000002095D834128>
SocketIO <pyclbr.Class object at 0x000002095D82FA20>
getfqdn <pyclbr.Function object at 0x000002095D8344E0>
create_connection <pyclbr.Function object at 0x000002095D834518>
getaddrinfo <pyclbr.Function object at 0x000002095D834550>这些功能可与自定义模块一起使用,以获取用户定义的类和方法的目录。
在下面的示例中,模块“triangles.py”用于获取其类结构。
#triangles.py
import math
class Triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
s=(self.a+self.b+self.c)/2
area=math.sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return area
class EquiTriangle(Triangle):
def __init__(self, a):
b = a
c = a
super().__init__(a,b,c)
def area(self):
area=math.sqrt(3)*pow(self.a,2)/4
return area现在,我们将在“三角形”模块中获取类和方法。
>>> br = pyclbr.readmodule_ex('triangles')
>>> for i,j in br.items(): print (i,j.methods)
Triangle {'__init__': 3, 'area': 7}
EquiTriangle {'__init__': 12, 'area': 16}pyclbr模块定义了两个对象–类对象和函数对象。
该函数对象具有以下属性
除上述对象外,Class对象还有两个属性