Created
February 1, 2016 21:09
-
-
Save AlecAivazis/78a01f0b8889ffbc69c1 to your computer and use it in GitHub Desktop.
A short python script showing the lifecycle methods of a metaclass
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
#!/usr/bin/env python3 | |
class Meta(type): | |
""" | |
Keeps track of classes derived from a base | |
""" | |
@classmethod | |
def __prepare__(cls, name, bases, **kwds): | |
return super().__prepare__(name, bases, **kwds) | |
def __new__(cls, name, bases, attributes, **kwds): | |
print('about to create {!r}'.format(name)) | |
record = super().__new__(cls, name, bases, attributes, **kwds) | |
print('created {!r}'.format(record)) | |
return record | |
def __init__(self, name, bases, attributes, **kwds): | |
super().__init__(name, bases, attributes, **kwds) | |
print('decorating {}'.format(self)) | |
# self.alec_foo = name | |
return | |
def __call__(self, **kwds): | |
return super().__call__(**kwds) | |
class Base(metaclass=Meta): | |
""" | |
Base class for keeping track of sublcasses | |
""" | |
alec_foo = 'Base' | |
def __init__(self, **kwds): | |
super().__init__(**kwds) | |
print('Base.__init__: {}'.format(self.alec_foo)) | |
self.alec_foo = 'mine' | |
print('Base.__init__: {}'.format(self.alec_foo)) | |
return | |
class Derived(Base): | |
""" | |
A derived class | |
""" | |
b = Base() | |
d = Derived() | |
# end of file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment