开发者

method __getattr__ is not inherited from parent class

Trying to subclass mechanize.Browser class:

from mechanize import Browser

class LLManager(Browser, object):
    IS_AUTHORIZED = False
    def __init__(self, login = "", passw = "", *args, **kwargs):
        super开发者_如何转开发(LLManager, self).__init__(*args, **kwargs)
        self.set_handle_robots(False)

But when I make something like this:

lm["Widget[LinksList]_link_1_title"] = anc

then I get an error:

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    lm["Widget[LinksList]_link_1_title"] = anc
TypeError: 'LLManager' object does not support item assignment

Browser class have overridden method __getattr__ as shown:

def __getattr__(self, name):
    # pass through _form.HTMLForm methods and attributes
    form = self.__dict__.get("form")
    if form is None:
        raise AttributeError(
            "%s instance has no attribute %s (perhaps you forgot to "
            ".select_form()?)" % (self.__class__, name))
    return getattr(form, name)

Why my class or instance don't get this method as in parent class?


Don't inherit from object, mechanize.Browser doesn't use new style classes. This should work as expected.

from mechanize import Browser

class LLManager(Browser):
    IS_AUTHORIZED = False
    def __init__(self, login = "", passw = "", *args, **kwargs):
        mechanize.Browser.__init__(self, *args, **kwargs)
        self.set_handle_robots(False)


You need to override __setattr__ to support assignment in this fashion. __getattr__ is only for retrieval


There's difference between items and attributes. Items are accessed using ob[item], while attributes are accessed using ob.item. The methods that define item assignment are __getitem__ and __setitem__, and the second is required if you're going to set items, not only access them. The methods __getattr__, __setattr__ and __getattribute__ deal with attributes, and don't help you here, and besides, the last two should be avoided because they complicate the creation of your class too much.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜