简体   繁体   English

方法__getattr__不是从父类继承的

[英]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: 浏览器类具有覆盖方法__getattr__ ,如下所示:

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? 为什么我的类或实例不像父类那样获得此方法?

You need to override __setattr__ to support assignment in this fashion. 您需要重写__setattr__以支持这种方式的分配 __getattr__ is only for retrieval __getattr__仅用于检索

There's difference between items and attributes. 项目和属性之间有区别。 Items are accessed using ob[item] , while attributes are accessed using ob.item . 使用ob[item]访问ob[item] ,而使用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. 定义项目分配的方法是__getitem____setitem__ ,如果要设置项目,不仅要访问它们,还需要第二个方法。 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. 方法__getattr____getattr__ __setattr____getattribute__处理属性,在这里没有帮助,此外,应避免最后两个方法,因为它们会使类的创建变得过于复杂。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM