JavaScript有对象字面量,例如
var p = {
name: "John Smith",
age: 23
}而.NET有匿名类型,例如
var p = new { Name = "John Smith", Age = 23}; // C#在Python中,可以通过(Ab)使用命名参数来模拟类似的东西:
class literal(object):
def __init__(self, **kwargs):
for (k,v) in kwargs.iteritems():
self.__setattr__(k, v)
def __repr__(self):
return 'literal(%s)' % ', '.join('%s = %r' % i for i in sorted(self.__dict__.iteritems()))
def __str__(self):
return repr(self)用法:
p = literal(name = "John Smith", age = 23)
print p # prints: literal(age = 23, name = 'John Smith')
print p.name # prints: John Smith但是这种代码被认为是Pythonic式的吗?
发布于 2010-07-26 21:46:10
您是否考虑过使用named tuple
使用你的口述符号
>>> from collections import namedtuple
>>> L = namedtuple('literal', 'name age')(**{'name': 'John Smith', 'age': 23})或关键字参数
>>> L = namedtuple('literal', 'name age')(name='John Smith', age=23)
>>> L
literal(name='John Smith', age=23)
>>> L.name
'John Smith'
>>> L.age
23可以很容易地将此行为封装到一个函数中
def literal(**kw):
return namedtuple('literal', kw)(**kw)等效于lambda的将是
literal = lambda **kw: namedtuple('literal', kw)(**kw)但就我个人而言,我认为给“匿名”函数命名是愚蠢的
发布于 2010-07-26 21:39:41
为什么不直接用字典呢?
p = {'name': 'John Smith', 'age': 23}
print p
print p['name']
print p['age']发布于 2010-07-26 22:23:00
来自ActiveState
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
# that's it! Now, you can create a Bunch
# whenever you want to group a few variables:
point = Bunch(datum=y, squared=y*y, coord=x)
# and of course you can read/write the named
# attributes you just created, add others, del
# some of them, etc, etc:
if point.squared > threshold:
point.isok = 1https://stackoverflow.com/questions/3335268
复制相似问题