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 的?
最佳答案
为什么不直接使用字典?
p = {'name': 'John Smith', 'age': 23}
print p
print p['name']
print p['age']
关于python - 对象文字是 Pythonic 的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3335268/