我们在学习的时候喜欢去写代码,或者进行代码的测试,在源代码的查看的进行的不多。大概很多是写完就放在一边,如果不是下次需要使用,也不会知道写的是否正确,还有没有可以修改或者改进的地方。所以,对于源代码的查看还是很有必要的,我们需要从发现中找到一些问题,接下来小编就教大家用inspect查找python3源代码的方法。
举个例子,用BeautifulSoup做分析,现在我们导入了两个库import inspect
from bs4 import BeautifulSoup
重点来了,当想看源代码的时候,可以用inspect.getsourcelines(BeautifulSoup)
输出是(['class BeautifulSoup(Tag):\n',
' """\n',
' This class defines the basic interface called by the tree builders.\n',
'\n',
' These methods will be called by the parser:\n',
' reset()\n',
' feed(markup)\n',
'\n',
' The tree builder may call these methods from its feed() implementation:\n',
' handle_starttag(name, attrs) # See note about return value\n',
' handle_endtag(name)\n',
' handle_data(data) # Appends to the current data node\n',
' endData(containerClass=NavigableString) # Ends the current data node\n',
'\n',
' No matter how complicated the underlying parser is, you should be\n',
" able to build a tree using 'start tag' events, 'end tag' events,\n",
' \'data\' events, and "done with data" events.\n',
'\n',
注释:太长了,我就截了一小段
如果你是用Python或者Notebook的话,inspect也可以查看你自己写的函数,用法和上面的一样。
但如果你是用terminal之类的Python编译,来查看自己定义的函数,则会引发IOError: could not get source code。
本篇小编用BeautifulSoup库带大家体验了一把查看源代码的感觉。