Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FooError(Exception):
- pass
- class Foo(object):
- def __init__(self, data):
- self.data = data
- def __repr__(self):
- return "%s(%s)" % (self.__class__.__name__, self.data)
- def __str__(self):
- return str(self.data)
- def __int__(self):
- try:
- return int(self.data)
- except ValueError:
- raise FooError("ValueError")
- def __float__(self):
- try:
- return float(self.data)
- except ValueError:
- raise FooError("ValueError")
- foo = Foo(42)
- bar = Foo("bar")
- print "s: %s | r: %r | %d | f: %f" % (foo, foo, foo, foo)
- str(foo) # %s calls __str__
- repr(foo) # %r calls __repr__
- float(foo) # %f calls __float__
- int(foo) # %d calls __int__
- str(bar) # %s calls __str__
- repr(bar) # %r calls __repr__
- # Will raise an error
- float(bar) # %f calls __float__
- int(bar) # %d calls __int__
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement