python成员变量可以在哪里声明_如何在python基类中声明成员变量

也许我做的不对,因为我在思考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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值