但是我有一组类,如下所示,它们有一组HTTP头(这是我封装HTTP请求的尝试)。例如,基类将具有最通用的头,而派生类将具有更专业的头。
在基类中,我不能只在一行上有header。这样做给了我一个语法错误。这样做如下,并设置为字典(它是)。但如果我在跑步的时候这么做,我会得到:
>>> 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"
如何在基类中创建成员变量,该变量也可以在派生类中访问?
我正在使用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"
通过在变量前面加上
self.
来引用您的header
变量您可以将
self
视为java、c++等的等价物关键字:指当前实例。在这里,您将
header
定义为一个类属性,这意味着可以使用httprequest.header
,self.header
(来自类内部)或my_instance.header
(来自类外部)。通过在
__init__
方法中声明它,可以使它成为实例变量(只能通过`self
或实例名访问):不过,在这里,你可能想把它保持在类级别。
实例变量总是通过类实例本身访问的。在方法内部,这是(按惯例)称为
self
。所以你需要使用self.headers
等请注意,通过在类的顶部定义
headers
,您定义了一个由所有成员共享的类变量。你不需要这样,也不需要在那里定义headers
。只要在__init__
内分配它。另外,正如StoryTeller所指出的,您需要在派生类方法中手动调用超类
__init__
方法,因为它首先定义了属性:为了让它工作,正如abarnert指出的,您需要从
object
继承基类。最后,请使用符合PEP8的名称:
PostHttpRequest
,等等相关问题 更多 >
编程相关推荐