Created
November 4, 2011 13:15
-
-
Save draftcode/1339284 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 Property(object): | |
| def __init__(self): | |
| self.name = None | |
| def setup_name(self, obj, cls): | |
| for k, v in cls.__dict__.iteritems(): | |
| if v is self: | |
| self.name = k | |
| obj.__dict__[k] = None | |
| return | |
| def __get__(self, obj, cls): | |
| if obj is None: | |
| return None | |
| if self.name is None: | |
| self.setup_name(obj, obj.__class__) | |
| return obj.__dict__[self.name] | |
| def __set__(self, obj, value): | |
| if self.name is None: | |
| self.setup_name(obj, obj.__class__) | |
| obj.__dict__[self.name] = value | |
| if __name__ == "__main__": | |
| class A(object): | |
| x = Property() | |
| obj = A() | |
| print A.x # => None | |
| print obj.x # => None | |
| obj.x = 10 | |
| print A.x # => None | |
| print obj.x # => 10 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment