Created
June 19, 2019 09:09
-
-
Save ayuLiao/726bfe335faf7a94bd125ee3936c4505 to your computer and use it in GitHub Desktop.
利用 __import__ 方法实现 Python 模型的懒加载
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 LazyImport: | |
def __init__(self, module_name): | |
self.module_name = module_name | |
self.module = None | |
def __getattr__(self, name): | |
if self.module is None: | |
self.module = __import__(self.module_name) | |
return getattr(self.module, name) | |
string = LazyImport("string") | |
print string.lowercase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment