maybe doing wrong because thinking how c++ classes work.
but have set of classes, see below, have set of http headers (it attempt @ encapsulating http requests). example, base class have generic header while derived classes have more specialised headers.
in base class, cannot have header on line itself. doing gave me syntax error. doing below , setting dictionary (which is). if when run get:
>>> 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' 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 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"
how create member variable in base class can accessed in derived classes?
i using python 2.7
edit. update based on understanding of responses. appear work :)
i getting typeerror seems saw in pythonwin debugger. not when run without debugger.
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 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"
instance variables accessed through class instance itself. inside method, (by convention) known self
. need use self.headers
etc.
note though defining headers
@ top of class, have defined class variable shared members. don't want this, , there no need define headers
there. assign within __init__
.
plus, storyteller points out, you'll need call superclass __init__
method manually inside derived class methods, since defines attribute in first place:
super(post_httprequest, self).__init__()
and in order work, abarnert points out, you'll need inherit base class object
.
finally, please use pep8-compliant names: posthttprequest
, etc.
Comments
Post a Comment