How can I create initialization code?
When I put the __init__
contructor always tell me that parameters are wrong.
Also please gave a example also using __new__
and one using super()
and why should we use or not use them.
import webapp2
class MainHandler( webapp2.RequestHandler ):
def __init__( self ):
#initialization code/vars
x = 1
def get( self ):
#code for get here
self.response.write( x+1 )
def post( self ):
#code for post here
self.response.write( x+2 )
app = webapp2.WSGIApplication ( [ ('/', MainHandler) ], debug=True )
Finally got it... The problem is that overriding "webapp2.RequestHandler" requires special special handling
from the webapp2 manual:
If you want to override the webapp2.RequestHandler.init() method, you must call webapp2.RequestHandler.initialize() at the beginning of the method. It’ll set the current request, response and appobjectsasattributesofthehandler. Example:
class MyHandler(webapp2.RequestHandler):
def __init__(self, request, response):
# Set self.request, self.response and self.app.
self.initialize(request, response)
# ... add your custom initializations here ...
# ...
...and that's it... now works as expected ;-)
If you aren't passing any arguments or including any of your own code in the __init__
method, there's usually no need to even create one. You'll just use webapp2.RequestHandler
's __init__
method.
If you do need to make one, you still have to call webapp2.RequestHandler.__init__
:
class theHandler(webapp2.RequestHandler):
def __init__(self, your_arg, *args, **kwargs):
super(theHandler, self).__init__(*args, **kwargs)
self.your_arg = your_arg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With