Python帮助函数调试函数 用于获取对象的属性及属性值

刚接触Python,上篇 《Python入门》第一个Python Web程序——简单的Web服务器 中调试非常不方便,不知道对象详细有什么属性,包括什么值,所以写了一个函数。用于获取对象的属性及属性值

函数代码例如以下:

#调试函数。用于输出对象的属性及属性值
def getAllAttrs(obj):
	strAttrs = ‘‘
	for o in dir(obj):
		strAttrs =strAttrs + o + ‘ := ‘ + str(getattr(obj,o)) + ‘<br />‘

	return strAttrs;

详细应用代码:

import os	#Python的标准库中的os模块包括普遍的操作系统功能

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler  #导入HTTP处理相关的模块

#调试函数。用于输出对象的属性及属性值
def getAllAttrs(obj):
	strAttrs = ‘‘
	for o in dir(obj):
		strAttrs =strAttrs + o + ‘ := ‘ + str(getattr(obj,o)) + ‘<br />‘

	return strAttrs;

#自己定义处理程序。用于处理HTTP请求
class TestHTTPHandler(BaseHTTPRequestHandler):
	#处理GET请求
    def do_GET(self):
		#页面输出模板字符串
        templateStr = ‘‘‘
<html>
<head>
<title>QR Link Generator</title>
</head>
<body>
%s
</body>
</html> ‘‘‘

	self.protocal_version = ‘HTTP/1.1‘	#设置协议版本号
	self.send_response(200)	#设置响应状态码
	self.send_header("Welcome", "Contect")	#设置响应头
	self.end_headers()
	self.wfile.write(templateStr % getAllAttrs(self))	#输出响应内容

#启动服务函数
def start_server(port):
    http_server = HTTPServer((‘‘, int(port)), TestHTTPHandler)
    http_server.serve_forever()	#设置一直监听并接收请求

os.chdir(‘static‘)	#改变工作文件夹到 static 文件夹
start_server(8000)	#启动服务。监听8000端口

输出例如以下:

MessageClass := mimetools.Message
__doc__ := None
__init__ := >
__module__ := __main__
address_string := >
client_address := (‘127.0.0.1‘, 38178)
close_connection := 1
command := GET
connection :=
date_time_string := >
default_request_version := HTTP/0.9
disable_nagle_algorithm := False
do_GET := >
end_headers := >
error_content_type := text/html
error_message_format :=
Error response

Error code %(code)d.

Message: %(message)s.

Error code explanation: %(code)s = %(explain)s.
finish := >
handle := >
handle_one_request := >
headers := Host: localhost:8000 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,en-GB;q=0.2 Cookie: bdshare_firstime=1451130349627
log_date_time_string := >
log_error := >
log_message := >
log_request := >
monthname := [None, ‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘, ‘May‘, ‘Jun‘, ‘Jul‘, ‘Aug‘, ‘Sep‘, ‘Oct‘, ‘Nov‘, ‘Dec‘]
parse_request := >
path := /
protocal_version := HTTP/1.1
protocol_version := HTTP/1.0
raw_requestline := GET / HTTP/1.1
rbufsize := -1
request :=
request_version := HTTP/1.1
requestline := GET / HTTP/1.1
responses := {200: (‘OK‘, ‘Request fulfilled, document follows‘), 201: (‘Created‘, ‘Document created, URL follows‘), 202: (‘Accepted‘, ‘Request accepted, processing continues off-line‘), 203: (‘Non-Authoritative Information‘, ‘Request fulfilled from cache‘), 204: (‘No Content‘, ‘Request fulfilled, nothing follows‘), 205: (‘Reset Content‘, ‘Clear input form for further input.‘), 206: (‘Partial Content‘, ‘Partial content follows.‘), 400: (‘Bad Request‘, ‘Bad request syntax or unsupported method‘), 401: (‘Unauthorized‘, ‘No permission -- see authorization schemes‘), 402: (‘Payment Required‘, ‘No payment -- see charging schemes‘), 403: (‘Forbidden‘, ‘Request forbidden -- authorization will not help‘), 404: (‘Not Found‘, ‘Nothing matches the given URI‘), 405: (‘Method Not Allowed‘, ‘Specified method is invalid for this resource.‘), 406: (‘Not Acceptable‘, ‘URI not available in preferred format.‘), 407: (‘Proxy Authentication Required‘, ‘You must authenticate with this proxy before proceeding.‘), 408: (‘Request Timeout‘, ‘Request timed out; try again later.‘), 409: (‘Conflict‘, ‘Request conflict.‘), 410: (‘Gone‘, ‘URI no longer exists and has been permanently removed.‘), 411: (‘Length Required‘, ‘Client must specify Content-Length.‘), 412: (‘Precondition Failed‘, ‘Precondition in headers is false.‘), 413: (‘Request Entity Too Large‘, ‘Entity is too large.‘), 414: (‘Request-URI Too Long‘, ‘URI is too long.‘), 415: (‘Unsupported Media Type‘, ‘Entity body in unsupported format.‘), 416: (‘Requested Range Not Satisfiable‘, ‘Cannot satisfy request range.‘), 417: (‘Expectation Failed‘, ‘Expect condition could not be satisfied.‘), 100: (‘Continue‘, ‘Request received, please continue‘), 101: (‘Switching Protocols‘, ‘Switching to new protocol; obey Upgrade header‘), 300: (‘Multiple Choices‘, ‘Object has several resources -- see URI list‘), 301: (‘Moved Permanently‘, ‘Object moved permanently -- see URI list‘), 302: (‘Found‘, ‘Object moved temporarily -- see URI list‘), 303: (‘See Other‘, ‘Object moved -- see Method and URL list‘), 304: (‘Not Modified‘, ‘Document has not changed since given time‘), 305: (‘Use Proxy‘, ‘You must use proxy specified in Location to access this resource.‘), 307: (‘Temporary Redirect‘, ‘Object moved temporarily -- see URI list‘), 500: (‘Internal Server Error‘, ‘Server got itself in trouble‘), 501: (‘Not Implemented‘, ‘Server does not support this operation‘), 502: (‘Bad Gateway‘, ‘Invalid responses from another server/proxy.‘), 503: (‘Service Unavailable‘, ‘The server cannot process the request due to a high load‘), 504: (‘Gateway Timeout‘, ‘The gateway server did not receive a timely response‘), 505: (‘HTTP Version Not Supported‘, ‘Cannot fulfill request.‘)}
rfile :=
send_error := >
send_header := >
send_response := >
server :=
server_version := BaseHTTP/0.3
setup := >
sys_version := Python/2.7.10
timeout := None
version_string := >
wbufsize := 0
weekdayname := [‘Mon‘, ‘Tue‘, ‘Wed‘, ‘Thu‘, ‘Fri‘, ‘Sat‘, ‘Sun‘]
wfile := 
时间: 2024-10-13 09:33:50

Python帮助函数调试函数 用于获取对象的属性及属性值的相关文章

【Python】[面性对象编程] 获取对象信息,实例属性和类属性

获取对象信息1.使用isinstance()判断class类型2.dir() 返回一个对象的所有属性和方法3.如果试图获取不存在的对象会抛出异常[AttributeError]4.正确利用对象内置函数的例子: def readImage(fp): if hasattr(fp,"read"): return readData(fp) return None 实例属性和类属性1.一句话,Python是动态语言,根据类创建的实例可以任意绑定属性.    注意:实例属性和雷属性的名字要保持不一

241 获取对象的属性名:Object.keys(对象)

Object.keys(对象) :获取到当前对象中的属性名 ,返回值是有元素为字符串的一个数组,效果类似 for-in. <script> // 用于获取对象自身所有的属性 var obj = { id: 1, pname: '小米', price: 1999, num: 2000 }; var arr = Object.keys(obj); console.log(arr); // ["id", "pname", "price",

python的operator.itemgetter(&#39;click&#39;)用于定义获取&#39;click&#39;项的函数

b = operator.itemgetter(1)  定义函数b,用于获取传入list的第1域的值 可以将b用于sort函数的key.作为排序的依据. adn_app_data_map是个字典 for key, app_arr in adn_app_data_map.items(): app_arr.sort(key=operator.itemgetter('click'), reverse=True) app_arr = app_arr[:3] keys = key.split('#') c

Python中的sorted函数以及operator.itemgetter函数

operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1,2,3] >>> b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值>>> b(a) 2 >>> b=operator.itemgetter(1,0)  //定义函数b,获取对象的第1个域和第0个的值>&

Python中的sorted函数以及operator.itemgetter函数 【转载】

operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1,2,3] >>> b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值>>> b(a) 2 >>> b=operator.itemgetter(1,0)  //定义函数b,获取对象的第1个域和第0个的值>&

Python常用内置函数介绍

Python提供了一个内联模块buildin.内联模块定义了一些开发中经常使用的函数,利用这些函数可以实现数据类型的转换.数据的计算.序列的处理等功能.下面将介绍内联模块中的常用函数. Python内置函数的基本用法可以查看Python安装目录下的doc目录下的说明文档,本文仅介绍Python典型的内置函数使用方法. reduce(function, iterable[, initializer]) 对序列的值进行累计计算 reduce()可以实现对序列进行连续处理的功能.reduce()的声明

Python:内置函数

1.abs() 取数字的绝对值,参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 >>> print(abs(-28))28>>> print(abs(-2.34))2.34>>> print(abs(1/3))0.3333333333333333 2.dict() 用于创建字典 >>> dict() #创建空字典{}>>> dict(a='who',b='while',c='whit') #传入关键字创建字

python中operator.itemgetter函数

operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. 1 k = [3,6,8] 2 b = operator.itemgetter(1) 3 print(b(k)) 4 #输出6 1 k = [3,6,8] 2 b = operator.itemgetter(2,0) 3 print(b(k)) 4 #输出(8, 3) 要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过

怎样获取对象的所有属性

使用Object.keys()可以获取对象本身所有的可遍历属性; 使用Object.getOwnPropertyNames()可以获取对象本身所有属性, 不管是否可遍历; 使用for...in...循环可以获取对象所有可遍历属性, 包括本身的属性和继承的属性; 使用下面的函数可以获取对象的所有属性, 不管是本身还是继承, 不管是可遍历还是不可遍历: function inheritedPropertyNames(obj) { var props = {}; while(obj) { Object