Created
October 27, 2015 17:32
-
-
Save ubershmekel/6cfd1d1aafee0253b43b to your computer and use it in GitHub Desktop.
Simple repr methods that allow you to reconstruct a simple object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
These two repr implementations make a "repr" that you can just drop into your class if it's a simple one. | |
""" | |
class A: | |
def __init__(self, x, y): | |
self.x = x | |
self.y = y | |
def __repr__(self): | |
return "%s(**%r)" % (self.__class__.__name__, self.__dict__) | |
print A(1,3) | |
# A(**{'y': 3, 'x': 1}) | |
class B: | |
def __init__(self, x, y): | |
self.x = x | |
self.y = y | |
def __repr__(self): | |
ctor_str = ', '.join('%s=%r' % pair for pair in (self.__dict__.items())) | |
return "%s(%s)" % (self.__class__.__name__, ctor_str) | |
print B(1,3) | |
# B(y=3, x=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The repr string it generates will only be correct if the class doesn't create it's own Data instance attribute - as all attributes go into self.dict. A full solution would need to use something like the inspect module to look at the arguments in the init method - an interesting programming challenge.