Last active
August 29, 2015 14:15
-
-
Save gfranxman/c581822edee832632c99 to your computer and use it in GitHub Desktop.
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
| class MyClass( object ): | |
| def __init__( self, a, b, c="somec", d="somed" ): | |
| self.a = a | |
| self._b = b | |
| self.__c = c | |
| self.__d__ = d | |
| def get_c(self): | |
| return self.__c | |
| def getD(self): | |
| return self.__d__ | |
| class MyReprdClass( MyClass, ReprFromInit ): | |
| pass | |
| >>> mc = MyClass( 1, 2 ) | |
| >>> mrc = MyReprdClass(3,4) | |
| >>> | |
| >>> mc | |
| <repr_from_init.MyClass object at 0x1070e8510> | |
| >>> mrc | |
| repr_from_init.MyReprdClass(a=3, b=4, c='somec', d='somed') | |
| >>> | |
| >>> mrc2 = MyReprdClass(3,4, c="another", d="yet more") | |
| >>> mrc2 | |
| repr_from_init.MyReprdClass(a=3, b=4, c='another', d='yet more') | |
| >>> |
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
| import inspect | |
| class ReprFromInit( object ): | |
| def __repr__( self ): | |
| args = inspect.getargspec( self.__class__.__init__ ).args | |
| path = "{modulename}.{classname}".format( modulename=self.__class__.__module__, classname=self.__class__.__name__ ) | |
| argstrs = [] | |
| for arg in args[1:]: # skip self | |
| for argname in [ arg, "_"+arg, '' ]: | |
| if hasattr( self, argname ): | |
| break | |
| if argname: | |
| a = getattr( self, argname ) | |
| val = a | |
| else: | |
| # might have a getter | |
| if hasattr( self, "get_"+arg ): | |
| val = eval( "self.get_{arg}()".format(arg=arg) ) | |
| elif hasattr( self, "get" + arg[0].upper() + arg[1:] ): | |
| val = eval( "self.get{arg}()".format(arg=arg[0].upper() + arg[1:]) ) | |
| else: | |
| val = "ERROR"#: cant find value for "+ arg+ "to create the repr" ) | |
| argstrs.append( "{k}={v}".format( k=arg, v=repr(val) ) ) | |
| argstr = ", ".join( argstrs ) | |
| constructor_call_str = "{p}({a})".format( p=path, a=argstr ) | |
| return constructor_call_str | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment