也许我做错了,因为我在思考 C++ 类是如何工作的。
但是我有一组类,见下文,其中有一组 HTTP header (这是我封装 HTTP 请求的尝试)。例如,基类将具有最通用的 header ,而派生类将具有更专业的 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"
如何在基类中创建一个在派生类中也可以访问的成员变量?
我正在使用 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"
最佳答案
实例变量总是通过类实例本身来访问。在方法内部,这(按照惯例)称为 self
。所以你需要使用self.headers
等
请注意,通过在类的顶部定义 headers
,您已经定义了一个由所有成员共享的 class 变量。你不想要这个,也没有必要在那里定义 headers
。只需在 __init__
中分配即可。
此外,正如 StoryTeller 指出的那样,您需要在派生类方法中手动调用父类(super class) __init__
方法,因为它首先定义了属性:
super(post_httprequest, self).__init__()
为了让它工作,正如 abarnert 指出的那样,您需要从 object
继承您的基类。
最后,请务必使用符合 PEP8 的名称:PostHttpRequest
等
关于python - 如何在python基类中声明可以在派生中访问的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661407/