dict AttributeError仅当通过点运算符访问时 [英] dict AttributeError only when accessing via dot operator

查看:66
本文介绍了dict AttributeError仅当通过点运算符访问时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在创建这样的字典:

So I am creating a dict like this:

request = {"method": "get"}

,当我尝试使用

print list(request.keys())

我得到了期望的结果:

['method']

我可以使用

来访问method属性

print request['method']

我得到了我期望的结果:

and I get what I'd expect:

get

但是,如果我尝试

print request.method

我得到一个错误

AttributeError:"dict"对象没有属性"method"

AttributeError: 'dict' object has no attribute 'method'

为什么我在使用.时出现错误,但是在使用方括号时却没有?

Why am I getting an error with a . but not when I use square brackets?

推荐答案

这两个操作转换为不同的方法调用:

The two operations translate into different method calls:

  • request['method'] translates into __getitem__
  • request.method translates into __getattribute__

Python中字典的API通过可下标的接口"工作.这意味着,可以通过get方法或[]索引访问其项目.

Dictionary's API in python works through "subscript-able interface". Meaning, its items are expected to be accessed through the get method or through [] index.

一个工作而另一个失败的原因是操作不等效.仅get[]起作用的原因是由于python中的实现.

The reason that one works and the other fails is that operations are not equivalent. The reason that only the get and [] works are due to the implementation in python.

通过覆盖 __getattr__ :

class AttrDict(dict):
    def __getattr__(self, name):
        return self[name]

request = AttrDict({'method': 'get'})
method = request.method  # 'get'

这篇关于dict AttributeError仅当通过点运算符访问时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆