Last active
September 17, 2016 04:33
-
-
Save T4rk1n/6df526d5e45aa7f9c6c2b2320091e81e to your computer and use it in GitHub Desktop.
Metaclass example
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
""" | |
Metaclass example by a metaddict. | |
Python 2: replace metaclass= by a class variable __metaclass__ = | |
""" | |
class Meta(type): | |
def __new__(mcs, cname, cbases, cdict): | |
meta_name = cname | |
new_class_dict = {} | |
for class_attribute_name, class_value in cdict.items(): | |
if class_attribute_name == 'meta_name': | |
meta_name = class_value | |
elif class_attribute_name == 'meta_object': | |
if issubclass(class_value.__class__, dict): | |
for key, value in class_value.items(): | |
new_class_dict[key] = value | |
# can you get functions to work with self ? | |
else: | |
new_class_dict[key] = value | |
return type.__new__(mcs, 'Meta%s' % meta_name, cbases, new_class_dict) | |
def factory(class_name, meta_shit={'hello':'world'}): | |
class NewMeta(metaclass=Meta): | |
meta_name = class_name | |
meta_object = meta_shit | |
return NewMeta() | |
if __name__ == '__main__': | |
meta_shit = factory("World") | |
print(meta_shit.__class__.__name__) | |
assert meta_shit.__class__.__name__ == 'MetaWorld' | |
assert hasattr(meta_shit, 'hello') | |
assert getattr(meta_shit, 'hello') == 'world' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment