如何在python基类中声明成员变量

2024-05-19 02:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

也许我做的不对,因为我在思考C++类是如何工作的。

但是我有一组类,如下所示,它们有一组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"

Tags: selfsendhttpgetinitrequestdefpost
2条回答

通过在变量前面加上self.来引用您的header变量

class httprequest:
    header = dict()  #dict of headers
    def __init__(self):
        #add standard headers
        self.header = { 'User-Agent' :  'Test Python http client v0.1' }

    def send(self):
        print "Sending base httprequest"

您可以将self视为java、c++等的等价物关键字:指当前实例。

在这里,您将header定义为一个类属性,这意味着可以使用 httprequest.headerself.header(来自类内部)或my_instance.header(来自类外部)。

通过在__init__方法中声明它,可以使它成为实例变量(只能通过`self或实例名访问):

class httprequest:

    def __init__(self):
        #add standard headers
        self.header = { 'User-Agent' :  'Test Python http client v0.1' }

    def send(self):
        print "Sending base httprequest"

不过,在这里,你可能想把它保持在类级别。

实例变量总是通过类实例本身访问的。在方法内部,这是(按惯例)称为self。所以你需要使用self.headers

请注意,通过在类的顶部定义headers,您定义了一个由所有成员共享的变量。你不需要这样,也不需要在那里定义headers。只要在__init__内分配它。

另外,正如StoryTeller所指出的,您需要在派生类方法中手动调用超类__init__方法,因为它首先定义了属性:

super(post_httprequest, self).__init__()

为了让它工作,正如abarnert指出的,您需要从object继承基类。

最后,请使用符合PEP8的名称:PostHttpRequest,等等

相关问题 更多 >

    热门问题