format(self)
在这种情况下如何工作?
class Commit:
number = None
sha = None
message = None
identity = None
def __init__(self, raw, number):
r = raw.commits[number]
self.number = number
self.sha = r['sha']
self.message = r['message']
self.identity = raw.identities[r['identity']]
def __str__(self):
return """
Commit {number} {sha}
Message {message}
Identity {identity}
""".format(self)
def __getitem__(self, attr):
return getattr(self, attr)
def __contains__(self, attr):
return hasattr(self, attr)
如果我然后尝试访问单个属性
c = Commit(raw, 170)
print(c['sha'])
例如,它有效。但是,如果我print(c)
直接说:
键错误:“数字”
我本来希望format()
通过__getitem__()
.
如何让它发挥作用?