Created
June 23, 2017 12:31
-
-
Save Kilerd/b0f51e66cc1a874fa450ca6cae98bb6b to your computer and use it in GitHub Desktop.
Alias Object
This file contains 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 Alias(object): | |
__alias__ = {} | |
def __getattr__(self, name): | |
try: | |
real_key = self.__alias__[name] | |
real_key_split = real_key.split(".") | |
if len(real_key_split) == 1: | |
return self.__getattribute__(real_key) | |
father = self | |
for child in real_key_split: | |
father = father.__getattribute__(child) | |
return father | |
except: | |
raise KeyError("object has no attribute {}".format(name)) | |
def __setattr__(self, key, value): | |
if key in self.__alias__: | |
real_key = self.__alias__[key] | |
else: | |
real_key = key | |
real_key_split = real_key.split(".") | |
if len(real_key_split) == 1: | |
object.__setattr__(self, real_key, value) | |
else: | |
father = self | |
deep_len = len(real_key_split) | |
for id, child in enumerate(real_key_split): | |
if id != deep_len - 1: | |
father = father.__getattribute__(child) | |
else: | |
object.__setattr__(father, child, value) | |
def alias(self, item, value): | |
self.__alias__[item] = value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment