说我有在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 2.7中嵌套的类似JSON的数据结构,我用一些外来的perl代码进行交换.我只想以amore pythonic方式"使用"这些列表和字典的嵌套结构.
所以如果我有这样的结构......
a = {
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 66 }],
}
Run Code Online (Sandbox Code Playgroud)
...我希望能够在python脚本中处理它,就好像它是嵌套的python classes/Structs一样,如下所示:
>>> aa = j2p(a) # <<- this is what I'm after.
>>> print aa.x
4
>>> aa.z = 99
>>> print a
{
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 66 }],
'z': 99
}
>>> aa.y[2].b = 999
>>> print a
{
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 999 }],
'z': 99
} …
Run Code Online (Sandbox Code Playgroud) 这是我正在考虑使用的模式:
class Dicty(dict):
def __init__(self):
self.__dict__ = self
d = Dicty()
d.foo = 'bar'
print d['foo']
>>> bar
d['foo'] = 'baz'
print d.foo
>>> 'baz'
Run Code Online (Sandbox Code Playgroud)
一般来说,我更喜欢对象属性访问的语义而不是dict get/set访问,但是在某些情况下需要类似dict的访问(例如d['foo-bar'] = 'baz'
),我宁愿不为这些情况使用特殊的getter setter方法,因此,dict和object同时具有共享属性的双重行为.
有上述模式的问题吗?
我正在寻找的是有这样的东西:
self.info['key'].attr2
Run Code Online (Sandbox Code Playgroud)
但我不确定实现它的最优雅的方式是什么。到目前为止,我已经定义了一个像下面这样的字典,但没有它的属性。
self.info = {}
self.info.update({'key':
{'attr1': 2,
'attr2': lambda: self.func(arg1)}
})
Run Code Online (Sandbox Code Playgroud)
但是我将不得不像这样使用它:
self.info['key']['attr2']()
Run Code Online (Sandbox Code Playgroud)
请注意,我正在寻找的是访问字典值(如属性)。这个线程有一个可以在我的情况下使用的答案,也可能是我从上面的子字典中创建一个对象并将其作为主字典的值。
但我想知道是否有更好的方法,也许使用装饰器和更少的代码行,甚至可能不使用字典来做我在第一行中描述的事情,也许更好:
self['key'].attr2
Run Code Online (Sandbox Code Playgroud) 我有一些python代码,如下所示:
procs = cpu_count()-1
if serial or procs == 1:
results = map(do_experiment, experiments)
else:
pool = Pool(processes=procs)
results = pool.map(do_experiment, experiments)
Run Code Online (Sandbox Code Playgroud)
设置serial
标志时它运行正常,但在Pool
使用时会出现以下错误.当我尝试打印出来的do_experiment
东西时,无法显示,所以我无法尝试/捕获并打印堆栈跟踪.
Exception in thread Thread-2:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 530, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 483, in run
self.__target(*self.__args, **self.__kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 285, in _handle_tasks
put(task)
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
什么是继续调试的好方法?
我无法使用点(.)访问字典键,但是当我定义一个继承自 dict 的类时,我可以使用点(.)访问它的键。有人能解释一下吗?
所以,当我运行这段代码时:
d = {'first_key':1, 'second_key':2}
d.first_key
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
'dict' object has no attribute 'first_key'
Run Code Online (Sandbox Code Playgroud)
但是当我运行这个时:
class DotDict(dict):
pass
d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)
Run Code Online (Sandbox Code Playgroud)
我明白了:
1
2
Run Code Online (Sandbox Code Playgroud) 我想写一个容器类
data['a']
,属性类访问,例如data.a
; 这是在这里解决的collections.OrderedDict
; 这是在这里解决的我将1.的解决方案改为子类collections.OrderedDict
而不是dict
它但不起作用; 见下文.
from collections import OrderedDict
class mydict(OrderedDict):
def __init__(self, *args, **kwargs):
super(mydict, self).__init__(*args, **kwargs)
self.__dict__ = self
D = mydict(a=1, b=2)
#D['c'] = 3 # fails
D.d = 4
#print D # fails
Run Code Online (Sandbox Code Playgroud)
带有失败注释的两行会导致以下错误:
print D
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 176, in __repr__
return '%s(%r)' % (self.__class__.__name__, self.items())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 113, in items
return [(key, self[key]) for key in self] …
Run Code Online (Sandbox Code Playgroud) 假设我们有一个班级:
class Foo (object):
... def __init__(self,d):
... self.d=d
... def return_d(self):
... return self.d
Run Code Online (Sandbox Code Playgroud)
......和一个字典:
d={'k1':1,'k2':2}
Run Code Online (Sandbox Code Playgroud)
......和一个实例:
inst=Foo(d)
Run Code Online (Sandbox Code Playgroud)
有没有办法动态添加属性return_d
:
inst.return_d.k1
会回1吗?
我有一个字典列表,我需要将字典值作为属性访问。
我的代码:
class Comments:
def __init__(self):
self.comments = [{'id': 1, 'title': 'bla'},
{'id': 2, 'title': 'bla2'},
{'id': 3, 'title': 'bla3'}]
def __iter__(self):
return iter(self.comments)
Run Code Online (Sandbox Code Playgroud)
所以,当我写类似的东西时:
comment_list = Comments()
for comment in comment_list:
print comment['id']
Run Code Online (Sandbox Code Playgroud)
有用。
但是我想使用属性comment.id
而不是comment['id']
。
如何实现呢?
我的json中有以下结构:
obj = {
'Name': 'David',
'Car': {
'Make': 'Ford',
'Year': 2008
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了点符号来引用对象值,例如:
Car.Make ==> 'Form'
Run Code Online (Sandbox Code Playgroud)
给定一个字符串,例如"Car.Make"
,我将如何以编程方式获取属性?在上面的例子中,它将是:
obj.get('Car').get('Make')
Run Code Online (Sandbox Code Playgroud)
但是对于一个深度嵌套的对象,我将如何提取给定点表示法的值"Attr1.Attr2.Attr3...Attrn"
?
python ×10
dictionary ×4
attributes ×2
class ×2
coding-style ×1
json ×1
list ×1
nested ×1
properties ×1
stack-trace ×1
syntax ×1