开发者

Accessing Parent Class' Property From Derived Class

I'm new to python and GAE and I thought python will act as any other OO language, but apparently not. How does __init__(self): function gives me different results in the following code?

class BaseHandler(webapp.RequestHandler):
    @property
    def current_user(self):
        if not hasattr(self, "_current_user"):
            self._current_user = None
            cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            user = User.get_by_key_name(cookie["uid"])

        return self._current_user

class SubmitHandler(BaseHandler):
    template_values = dict(facebook_app_id=FACEBOOK_APP_ID)

    def __init__(self):
        #throws error : AttributeError: 'SubmitHandler' object has no attribute 'request'
        self.template_values['current_user'] = self.current_user

    def get(self):
        #this one function is error free
        self.template_values['current_user'] = self.current_user

Ho开发者_如何学Cw do I access the class' parent property?


If you look at your SubmitHandler class you'll notice that it indeed does not have a request attribute -- at least, none you set, and none you give the parent class a chance to set. Perhaps what you need to do is call the parentclass __init__ method before you try to access self.current_user.

As a side note, you should realize that the template_values dict you define inside the SubmitHandler class there is a class attribute, and thus shared between all instances of the class. Since you assign it something instance-specific in your __init__, you probably mean for it to be an instance attribute instead. Assign it to self.template_values in your __init__ method.


There's nothing particularly different about Python's object inheritance.

By defining __init__, you have told Python that this is all that needs to be done to initialize the object. You're therefore denying it the chance to run the superclass's initialization code. You need to call super:

def __init__(self, *args, **kwargs):
    super(SubmitHandler, self).__init__(*args, **kwargs)
    self.template_values['current_user'] = self.current_user

This might however not solve your problem - you're failing to take into account the possibility that self.request is initialized at another point in the program, which is why it works by the time get is called.


self.request and self.response are not set by the class constructor in webapp. They're set later, when the framework calls the handler's initialize method. You can override this, just make sure you call the parent class's initialize before doing anything else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜