也许我做的不对,因为我在思考C++类是如何工作的。
但是我有一组类,如下所示,它们有一组HTTP头(这是我封装HTTP请求的尝试)。例如,基类将具有最通用的头,而派生类将具有更专业的头。
在基类中,我不能只在一行上有header。这样做给了我一个语法错误。这样做如下,并设置为字典(它是)。但如果我在跑步的时候这么做,我会得到:>>> Unhandled exception while debugging...
Traceback (most recent call last):
File "C:\Python27\rq_module.py", line 1, in
class httprequest:
File "C:\Python27\rq_module.py", line 2, in httprequest
header #dict of headers
NameError: name 'header' is not defined
class httprequest:
header = dict() #dict of headers
def __init__(self):
#add standard headers
header = { 'User-Agent' : 'Test Python http client v0.1' }
def send(self):
print "Sending base httprequest"
class get_httprequest(httprequest):
"""GET http requests class"""
def send(self):
print "Sending GET http request"
class post_httprequest(httprequest):
"""POST http request class"""
def __init__(self):
header += { 'Content-Type' : 'application/json' } #all data sent in json form
def send(self):
print "Sending POST http request"
如何在基类中创建成员变量,该变量也可以在派生类中访问?
我正在使用Python2.7
编辑。这是基于我对回答的理解的更新。似乎确实有效:)
我收到了一个TypeError,但似乎我只在PythonWin调试器中看到了它。当我运行时没有调试器。class httprequest(object):
header = dict() #dict of headers
def __init__(self):
print "httprequest ctor"
self.header['User-Agent'] = 'Test Python http client v0.1'
def send(self):
print "Sending base httprequest"
class get_httprequest(httprequest):
"""GET http requests class"""
def send(self):
print "Sending GET http request"
class post_httprequest(httprequest):
"""POST http request class"""
def __init__(self):
super(post_httprequest, self).__init__()
super(post_httprequest, self).header['Content-Type'] = 'application/json'
print "post_httprequest ctor"
def send(self):
print "Sending POST http request"