Created
August 21, 2017 07:51
-
-
Save geekKeen/26e890aae9b2eecd60f996d16cfd60e4 to your computer and use it in GitHub Desktop.
__call__ 函数的使用
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 NoInstance(type): | |
def __call__(self, *args, **kwargs): | |
raise TypeError('Cannot instantiate directly') | |
class Spam1(object): | |
__metaclass__ = NoInstance | |
class Spam2(object): | |
def __call__(self, *args, **kwargs): | |
raise TypeError('Cannot instantiate directly') | |
if __name__ == '__main__': | |
s1 = Spam1() # raise TypeError | |
s2 = Spam2() | |
s2() # raise TypeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
可以看出
__call__
是类实例调用时调用 ,所以可以使用元类控制类,不允许类实例化