方法 __getattr__ 不是从父类继承的
尝试子类 mechanize.Browser 类:
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)
但是当我做这样的事情时:
lm["Widget[LinksList]_link_1_title"] = anc
然后我收到错误:
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
浏览器类已重写方法 __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)
为什么我的类或实例没有像父类中那样获取此方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要从对象继承,mechanize.Browser 不使用新样式类。这应该按预期工作。
Don't inherit from object, mechanize.Browser doesn't use new style classes. This should work as expected.
您需要重写 __setattr__ 来支持这种方式的赋值。
__getattr__
仅用于检索You need to override
__setattr__
to support assignment in this fashion.__getattr__
is only for retrieval物品和属性之间存在差异。使用
ob[item]
访问项目,使用ob.item
访问属性。定义项目分配的方法是__getitem__
和__setitem__
,如果您要设置项目(而不仅仅是访问它们),则需要第二个方法。方法__getattr__
、__setattr__
和__getattribute__
处理属性,在这里对您没有帮助,此外,应该避免最后两个,因为它们使你的类的创建变得过于复杂。There's difference between items and attributes. Items are accessed using
ob[item]
, while attributes are accessed usingob.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.