method __getattr__ is not inherited from parent class

1.9k views Asked by At

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?

3

There are 3 answers

0
cerberos On BEST ANSWER

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)
4
Daniel DiPaolo On

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

1
Rosh Oxymoron On

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.