【发布时间】:2019-12-02 12:30:13
【问题描述】:
我有一个带有__getitem__() 函数的类,它可以像字典一样订阅。但是,当我尝试将其传递给str.format() 时,我得到了TypeError。如何在 python 中使用 format() 函数的类?
>>> class C(object):
id=int()
name=str()
def __init__(self, id, name):
self.id=id
self.name=name
def __getitem__(self, key):
return getattr(self, key)
>>> d=dict(id=1, name='xyz')
>>> c=C(id=1, name='xyz')
>>>
>>> #Subscription works for both objects
>>> print(d['id'])
1
>>> print(c['id'])
1
>>>
>>> s='{id} {name}'
>>> #format() only works on dict()
>>> print(s.format(**d))
1 xyz
>>> print(s.format(**c))
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print(s.format(**c))
TypeError: format() argument after ** must be a mapping, not C
【问题讨论】:
-
看来你的问题不在于
format(),而在于**。 -
但是我删除它并去
print(s.format(c))它会引发 KeyError -
c.__dict__会给你内部字典。但我建议添加一些属性来返回它,而不是直接返回它。你也可以让C继承自dict,而不是object。 -
是的,使用
print(s.format(**c.__dict__))可以解决问题。谢谢
标签: python python-3.x string mapping typeerror