views:

104

answers:

4

hi,

in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to define a '%M' (or some such) which would then dump the entire contents of the matrix...

thanks

+4  A: 

Defining the __str__()/__unicode__() and/or __repr__() methods will let you use the existing %s and %r format specifiers as you like.

Ignacio Vazquez-Abrams
yes i know. i want to define something different. basically something similar to variadic C functions...
anupam
@anupam: http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_Python
voyager
A: 

I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define the str method of the class to adjust it's output according to how it was set. Then the main print statement would still use a '%s' specifier, and call your custom str.

rldrenth
A: 

If you really want to use custom specifiers you cannot do this in way that compatible with the rest of the Python language and standard library. Take advantage of what Python already supplies (%s and %r) and customise it for your needs by overriding __str__() or __repr__()

class Matrix(object):
    def __str__(self):
        return convert_to_pretty_matrix_string(self)
    def __repr__(self):
        return convert_to_textual_matrix_format(self)
Tendayi Mawushe
A: 

not sure how to add a large comment. but basically, this is what i wanted to say:


hmm, actually the matrix thingie was just an example. ok, so basically what i really have is a bit-banging python program to drive an lcd display. now, to dump characters on the display, i would like the users to start using a printf like routine i.e.

printf(row, column, fmt_args, **fmt_kwds)

now, most of the lcd displays are hd44780 compatible. apart from the usual ascii character set (plus some other vendor specific characters) allow users to define their own custom shapes e.g. say a bell or a bar (which fits into a 5x8 pattern).

in order to continue using the 'printf' interface above, i need some way for the user to specify a custom character say '%Z', and hence the question...

sorry, couldn't make it shorter...

anupam