0
4

2 回答 2

2

There isn't. This customizability is one of the major benefits of the format method over % formatting. If it wasn't novel, PEP 3101 wouldn't need to discuss this aspect of it in so much detail.

If you need to support older versions of Python than have new-style string formatting, the best you can do is to implement a custom conversion function on your class, and expect clients to call it like this:

'%4f %s' % (5, myobj.str('<'))
于 2013-05-07T13:47:32.697 回答
-1

You might find this helpful: operator overloading in python

__mod__ and __rmod__ are included here: http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

Don't bother trying to reinvent Python's string formatting mini-language...use it to your advantage: http://docs.python.org/2/library/string.html#format-specification-mini-language

EDIT: you probably got at least this far, but since we're here to code:

class moddableObject(object):
    def __mod__(self, arg)
        return 'got format arg: {}'.format(arg)

moddable = moddableObject()
print moddable % 'some string'
于 2013-05-07T13:06:26.203 回答