也许我做错了因为我正在思考C++类是如何工作的.
但我有一组类,见下文,它们有一组HTTP头(这是我尝试封装HTTP请求).例如,基类将具有最通用的头,而派生类将具有更多专用头.
在基类中,我不能只在一行上有标题.这样做给了我一个语法错误.所以像下面这样做,并设置为字典(它是).但是,如果我在跑步时这样做,我得到:
>>> Unhandled exception while debugging...
Traceback (most recent call last):
File "C:\Python27\rq_module.py", line 1, in <module>
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"
Run Code Online (Sandbox Code Playgroud)
如何在基类中创建成员变量,也可以在派生类中访问?
我使用的是Python 2.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"
Run Code Online (Sandbox Code Playgroud)
实例变量总是通过类实例本身访问.在方法内部,这是(按惯例)称为self.所以你需要使用self.headers等
请注意,通过headers在类的顶部定义,您已定义了一个由所有成员共享的类变量.你不想要这个,也没有必要在headers那里定义.只需将其分配即可__init__.
另外,正如StoryTeller指出的那样,你需要__init__在派生类方法中手动调用超类方法,因为它首先定义了属性:
super(post_httprequest, self).__init__()
Run Code Online (Sandbox Code Playgroud)
为了实现这一点,正如abarnert指出的那样,你需要从中继承你的基类object.
最后,请使用符合PEP8的名称:PostHttpRequest等.
| 归档时间: |
|
| 查看次数: |
7242 次 |
| 最近记录: |