How is the __format__ method supposed to be used for int?

你说的曾经没有我的故事 提交于 2021-01-22 06:54:22

问题


I saw there was a __format__ method but help(int.__format__) doesn't provide any help.

I also know you're not suppose to call a __method__ directly. When is this method called? Which is its argument?


回答1:


It's used for Py3k's new string formatting scheme.

You can find more info here:

http://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting

You are right that it isn't called directly. It's called by str.format or the new format builtin.




回答2:


It's used when you pass an integer to the format() function. The details elude me, as I can't seem to get it to tell me what exactly the argument is. (Edit: see lost-theory's link)

Oh, and it only works when the integer is the only argument. If you pass a tuple to format, then the tuple.__format__ function is called, and the int.__str__ or something.

'{0}'.format(4)
str(4.__format__(format_spec=''))


来源:https://stackoverflow.com/questions/2179926/how-is-the-format-method-supposed-to-be-used-for-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!