Created
April 23, 2014 15:01
-
-
Save Ogreman/11218810 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
import itertools | |
def name_func(var, scope=globals): | |
try: | |
return itertools.ifilter( | |
lambda x: var is scope().get(x), | |
scope().keys() | |
).next() | |
except StopIteration: | |
return None | |
class NamedVar(type): | |
def __new__(meta, name, bases, dct): | |
dct['__varname__'] = property(name_func) | |
return type.__new__(meta, name, bases, dct) | |
class A(object): | |
__metaclass__ = NamedVar | |
def __init__(self, v=0): | |
self._val = v | |
def __repr__(self): | |
return '{var}: {val}'.format( | |
var=self.__varname__, | |
val=self._val | |
) | |
if __name__ == '__main__': | |
a = A() | |
b = A(1) | |
c = A(1) | |
print (a, b, c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment