12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

class addrepr(adder): # Inherit _ _init_ _, _ _add_ _... def _ _repr_ _(self): # Add string representation... return 'addrepr(%s)' % self.data # Convert to string as code...>>> x = addrepr(2) # Runs _ _init_ _>>> x + 1 # Runs _ _add_ _>>> x # Runs _ _repr_ _addrepr(3)>>> print x # Runs _ _repr_ _addrepr(3)>>> str(x), repr(x) # Runs _ _repr_ _('addrepr(3)', 'addrepr(3)')So why two display methods? Roughly, _ _str_ _ is tried first for user-friendly displays,such as the print statement, and the str built-in function. The _ _repr_ _ methodshould in principle return a string that could be used as executable code to re-createthe object; it’s used for interactive prompt echoes, and the repr function. If no _ _str_ _is present, <strong>Python</strong> falls back on _ _repr_ _ (but not vice versa):>>> class addstr(adder):... def _ _str_ _(self): # _ _str_ _ but no _ _repr_ _... return '[Value: %s]' % self.data # Convert to nice string...>>> x = addstr(3)>>> x + 1>>> x # Default repr>>> print x # Runs _ _str_ _[Value: 4]>>> str(x), repr(x)('[Value: 4]', '')Because of this, _ _repr_ _ may be best if you want a single display for all contexts. Bydefining both methods, though, you can support different displays in different contexts—forexample, an end-user display with _ _str_ _, and a low-level display forprogrammers to use during development with _ _repr_ _:>>> class addboth(adder):... def _ _str_ _(self):... return '[Value: %s]' % self.data # User-friendly string... def _ _repr_ _(self):... return 'addboth(%s)' % self.data # As-code string...>>> x = addboth(4)>>> x + 1>>> x # Runs _ _repr_ _addboth(5)>>> print x # Runs _ _str_ _[Value: 5]>>> str(x), repr(x)('[Value: 5]', 'addboth(5)')Operator Overloading | 501

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!