Advertisement
DeaD_EyE

repr, str, int, float magic...

Jun 28th, 2015
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. class FooError(Exception):
  2.     pass
  3.  
  4. class Foo(object):
  5.  
  6.     def __init__(self, data):
  7.         self.data = data
  8.     def __repr__(self):
  9.         return "%s(%s)" % (self.__class__.__name__, self.data)
  10.  
  11.     def __str__(self):
  12.         return str(self.data)
  13.  
  14.     def __int__(self):
  15.         try:
  16.             return int(self.data)
  17.         except ValueError:
  18.             raise FooError("ValueError")
  19.  
  20.     def __float__(self):
  21.         try:
  22.             return float(self.data)
  23.         except ValueError:
  24.             raise FooError("ValueError")
  25.    
  26.  
  27. foo = Foo(42)
  28. bar = Foo("bar")
  29.  
  30. print "s: %s | r: %r | %d | f: %f" % (foo, foo, foo, foo)
  31. str(foo) # %s calls __str__
  32. repr(foo) #  %r calls __repr__
  33. float(foo) #  %f calls __float__
  34. int(foo) #  %d calls __int__
  35.  
  36.  
  37. str(bar) # %s calls __str__
  38. repr(bar) #  %r calls __repr__
  39.  
  40. # Will raise an error
  41. float(bar) #  %f calls __float__
  42. int(bar) #  %d calls __int__
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement