Skip to content

Instantly share code, notes, and snippets.

@pahaz pahaz/metaclasses.py
Created Aug 25, 2016

Embed
What would you like to do?
Short story about how metaclasses work
print('class Meta(type)')
class Meta(type):
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
print(' Meta.__prepare__(mcs=%s, name=%r, bases=%s, **%s)' % (
mcs, name, bases, kwargs
))
return super().__prepare__(mcs, name, bases)
@staticmethod
def __new__(mcs, name, bases, attrs, **kwargs):
print(' Meta.__new__(mcs=%s, name=%r, bases=%s, attrs=[%s], **%s)' % (
mcs, name, bases, ', '.join(attrs), kwargs
))
return super().__new__(mcs, name, bases, attrs)
def __init__(cls, name, bases, attrs, **kwargs):
print(' Meta.__init__(cls=%s, name=%r, bases=%s, attrs=[%s], **%s)' % (
cls, name, bases, ', '.join(attrs), kwargs
))
return super().__init__(name, bases, attrs)
def __call__(cls, *args, **kwargs):
print(' Meta.__call__(cls=%s, args=%s, kwargs=%s)' % (
cls, args, kwargs
))
return super().__call__(*args, **kwargs)
def __getattribute__(cls, name):
print(' Meta.__getattribute__(cls=%s, name=%s)' % (cls, name))
return super().__getattribute__(name)
print('class Class(metaclass=Meta)')
class Class(metaclass=Meta):
@staticmethod
def __new__(cls, *args, **kwargs):
print(' Class.__new__(cls=%s, args=%s, kwargs=%s)' % (
cls, args, kwargs
))
return super().__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print(' Class.__init__(self=%s, args=%s, kwargs=%s)' % (
self, args, kwargs
))
return super().__init__(*args, **kwargs)
def __getattribute__(self, name):
print(' Class.__getattribute__(self=%s, name=%s)' % (self, name))
return super().__getattribute__(name)
def foo(self):
print('Class.foo(%s)' % self)
def bar(self, *args, **kwargs):
print('Class.bar(%s, *%r, **%r)' % (self, args, kwargs))
print('class SubClass(Class)')
class SubClass(Class):
def foo(self):
print('SubClass.foo(%s)' % self)
print('instances')
a = SubClass()
a.bar(1, a=2)
a.foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.