对象字面量是 Pythonic 的吗?
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 吗?
JavaScript has object literals, e.g.
var p = {
name: "John Smith",
age: 23
}
and .NET has anonymous types, e.g.
var p = new { Name = "John Smith", Age = 23}; // C#
Something similar can be emulated in Python by (ab)using named arguments:
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)
Usage:
p = literal(name = "John Smith", age = 23)
print p # prints: literal(age = 23, name = 'John Smith')
print p.name # prints: John Smith
But is this kind of code considered to be Pythonic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
为什么不直接使用字典呢?
Why not just use a dictionary?
您是否考虑过使用 命名元组?
使用你的字典表示法
或关键字参数
可以很容易地将这种行为包装到一个函数中,
就像 lambda 等价物一样,
但我个人认为给“匿名”函数命名是愚蠢的
Have you considered using a named tuple?
Using your dict notation
or keyword arguments
It is possible to wrap this behaviour into a function easily enough
the lambda equivalent would be
but personally I think it's silly giving names to "anonymous" functions
来自 ActiveState:
From ActiveState:
我想说你实现的解决方案看起来很Pythonic;话虽如此,
types.SimpleNamespace
(记录在此处) 已经封装了这个功能:I'd say that the solution you implemented looks pretty Pythonic; that being said,
types.SimpleNamespace
(documented here) already wraps this functionality:我不认为创建“匿名”类/实例有什么问题。在一行代码中通过简单的函数调用来创建一个通常非常方便。我个人使用这样的东西:
对于创建虚拟对象,它工作得很好。 Namedtuple 还可以,但是它是不可变的,这有时会很不方便。字典是......好吧,字典,但在某些情况下,您必须传递定义了
__getattr__
的内容,而不是__getitem__
。我不知道它是否是Pythonic,但它有时会加快速度,对我来说,这是使用它的充分理由(有时)。
I don't see anything wrong with creating "anonymous" classes/instances. It's often very convienient to create one with simple function call in one line of code. I personally use something like this:
For creating dummy objects it works just fine. Namedtuple is ok, but is immutable, which can be inconvenient at times. And dictionary is... well, a dictionary, but there are situations when you have to pass something with
__getattr__
defined, instead of__getitem__
.I don't know whether it's pythonic or not, but it sometimes speeds things up and for me it's good enough reason to use it (sometimes).
来自 Python IAQ:
From the Python IAQ:
我认为对象字面量在 JavaScript 中有意义有两个原因:
在 JavaScript 中,对象是创建具有字符串索引属性的“事物”的唯一方法。在 Python 中,正如另一个答案中所述,字典类型可以做到这一点。
JavaScript 的对象系统是基于原型的。 JavaScript 中没有类这样的东西(尽管它会在未来的版本中出现)——对象具有原型对象而不是类。因此,通过文字“从无到有”创建一个对象是很自然的,因为所有对象只需要内置的根对象作为原型。在Python 中,每个对象都有一个类——您应该将对象用于具有多个实例的事物,而不仅仅是一次性的。
因此,对象字面量不是 Pythonic,但它们是 JavaScripthonic。
I think object literals make sense in JavaScript for two reasons:
In JavaScript, objects are only way to create a “thing” with string-index properties. In Python, as noted in another answer, the dictionary type does that.
JavaScript‘s object system is prototype-based. There’s no such thing as a class in JavaScript (although it‘s coming in a future version) — objects have prototype objects instead of classes. Thus it’s natural to create an object “from nothing”, via a literal, because all objects only require the built-in root object as a prototype. In Python, every object has a class — you’re sort of expected to use objects for things where you’d have multiple instances, rather than just for one-offs.
Thus no, object literals aren’t Pythonic, but they are JavaScripthonic.
对于大多数情况来说,一个简单的字典就足够了。
如果您正在寻找与您为字面情况指定的 API 类似的 API,您仍然可以使用字典并简单地覆盖特殊的
__getattr__
函数:注意:请记住,与命名元组相反,字段是未经验证,你有责任确保你的论点是合理的。字典中允许使用诸如
p['def'] = 'something'
之类的参数,但您无法通过p.def
访问它们。A simple dictionary should be enough for most cases.
If you are looking for a similar API to the one you indicated for the literal case, you can still use dictionaries and simply override the special
__getattr__
function:Note: Keep in mind though that contrary to namedtuples, fields are not validated and you are in charge of making sure your arguments are sane. Arguments such as
p['def'] = 'something'
are tolerated inside a dictionary but you will not be able to access them viap.def
.