Shi*_*oir 42 python object-literal
JavaScript有对象文字,例如
var p = {
  name: "John Smith",
  age:  23
}
和.NET有匿名类型,例如
var p = new { Name = "John Smith", Age = 23}; // C#
类似的东西可以通过(ab)使用命名参数在Python中模拟:
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吗?
Way*_*ner 67
为什么不用字典呢?
p = {'name': 'John Smith', 'age': 23}
print p
print p['name']
print p['age']
Joh*_*ooy 39
您是否考虑使用命名元组?
使用你的字母表示法
>>> 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)
但就个人而言,我认为给"匿名"功能命名是愚蠢的
pil*_*her 10
来自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 = 1
| 归档时间: | 
 | 
| 查看次数: | 15422 次 | 
| 最近记录: |