相关疑难解决方法(0)

像属性一样访问dict键?

我发现访问dict密钥更加方便,obj.foo而不是obj['foo'],所以我写了这个代码片段:

class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value
Run Code Online (Sandbox Code Playgroud)

但是,我认为必须有一些原因,Python不提供开箱即用的功能.以这种方式访问​​dict密钥有什么警告和陷阱?

python syntax dictionary

273
推荐指数
16
解决办法
16万
查看次数

通过属性和索引访问递归访问dict?

我希望能够做到这样的事情:

from dotDict import dotdictify

life = {'bigBang':
           {'stars':
               {'planets': []}
           }
       }

dotdictify(life)

# This would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
# But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {}}

#Also creating new child objects if none exist, using the following syntax:
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}
Run Code Online (Sandbox Code Playgroud)

我的动机是改进代码的简洁性,如果可能的话,使用与Javascript类似的语法来访问JSON对象,以实现高效的跨平台开发.(我也使用Py2JS和类似的.)

python oop dictionary getattr

26
推荐指数
2
解决办法
9690
查看次数

在Python中轻松地从/向名称空间/词典转储变量

说我有在Python几个变量或对象a,b,c,...

如何轻松地这些变量转储到Python中的命名空间中并在以后恢复它们?(例如,以相同的方式argparse将各种变量包装到命名空间中).

以下是我希望如何在命名空间之间转储内容的两个示例:

将局部变量转储到命名空间中

function (bar):
   # We start with a, b and c
   a = 10
   b = 20
   c = "hello world"

   # We can dump anything we want into e, by just passing things as arguments:
   e = dump_into_namespace(a, b, c) 
   del a, b, c

   print (e.a + e.b) # Prints 30
   return e  # We can return e if we want. This is just …
Run Code Online (Sandbox Code Playgroud)

python syntax dictionary nested

10
推荐指数
2
解决办法
3447
查看次数

标签 统计

dictionary ×3

python ×3

syntax ×2

getattr ×1

nested ×1

oop ×1