Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created August 21, 2017 07:51
Show Gist options
  • Save geekKeen/26e890aae9b2eecd60f996d16cfd60e4 to your computer and use it in GitHub Desktop.
Save geekKeen/26e890aae9b2eecd60f996d16cfd60e4 to your computer and use it in GitHub Desktop.
__call__ 函数的使用
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
@geekKeen
Copy link
Author

geekKeen commented Aug 21, 2017

可以看出
__call__ 是类实例调用时调用 ,所以可以使用元类控制类,不允许类实例化

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment