Sunday, 27 October 2013

Built-in __repr__ and Internal Functions

__repr__ not __str__

This past week, we learned about a built-in function which was, to me, entirely new. It was presented to us in class under the heading "prefer repr to str" as follows:
repr is supposed to provide explicit information about an object and is returned when the class object itself is meant to be returned and str is what you want returned when print() is called on it. However, as we learned in lecture, repr acts as the substitute for str when no str method is defined for that class. So, classes should always have a repr method, whereas str is optional.

Internal functions

We also learned about defining functions under other function headers. At first this seemed like an entirely useless technique especially when the instructor mentioned that it is very hard to access the internal function individually from elsewhere. But, I made sure to clear up my conclusion and the answer I received was that a function with a generic name doing almost identical tasks might be required in many different functions in a file. This way, these internal functions can share a name yet have a slightly different implementation, which could be a very useful tool for programmers coding complicated classes.

No comments:

Post a Comment