使用字典 vs 类的 __dict__ 方法格式化字符串

2 投票
2 回答
2051 浏览
提问于 2025-04-16 17:11

我一直在用字典来格式化字符串。

s = '%(name1)s %(name2)s'
d = {}
d['name1'] = 'asdf'
d['name2'] = 'whatever'
result = s % d

我刚意识到我可以用一个类和dict方法来做到这一点。

s = '%(name1)s %(name2)s'
class D : pass
d = D()
d.name1 = 'asdf'
d.name2 = 'whatever'
result = s % d.__dict__

(显然,我这样做是为了处理更长的字符串和更多的键)。

使用类的方法有没有什么我没想到的缺点?或者有没有更好的字符串格式化方法我没发现?

谢谢。

2 个回答

2

你还可以考虑用关键字参数来创建字典,比如:

d = dict(name1='foo', name2='bar')

或者使用格式化的关键字参数:

"{name1} baz {name2}".format(name1='foo', name2='bar')
8

你可以使用新的格式化方式,这种方式允许在格式字符串中使用getattr和getitem操作符:

>>> class X(object):
...     pass
... 
>>> x = X()
>>> x.x = 1
>>> d = {'a':1, 'b':2}
>>> "{0[a]} {0[b]} {1.x}".format(d, x)
'1 2 1'

关于你方法的缺点——对象的__dict__只包含特定实例所拥有的属性和方法,所以任何在类级别定义的属性或方法都会失败:

>>> class X(object):
...     x1 = 1
... 
>>> x = X()
>>> x.x2 = 2
>>> x.__dict__
{'x2': 2}
>>> x.x1
1
>>> x.__dict__['x1']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x1'

它也不适用于__slots____getattribute__的重写。

撰写回答