Last active
September 23, 2020 04:58
-
-
Save baileywickham/5db487d33de21e6c4a0e8a092dadca2b to your computer and use it in GitHub Desktop.
Metaclasses in python
This file contains hidden or 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
# Create classes based on csv file data | |
with open("file.csv", 'r') as f: | |
header = f.readline().split(',') | |
metaclass = type('csv', (object,), {h:None for h in header}) | |
for line in f.readlines(): | |
m = metaclass() | |
line = line.split(',') | |
for i in range(len(header)): | |
setattr(m, header[i], line[i]) | |
yield m # Return as generator | |
# These are equivilent definitions | |
class X: | |
a = 1 | |
def hello(self, k): | |
return k | |
a = type('Y', (object,), {'a':1, 'hello':lambda self, k: k}) | |
print(a().hello('hello from a metaclass')) | |
# This is equivilent to X(), instances are created with __new__, | |
# which returns an instance to be initated by __init__. | |
x = object.__new__(X) | |
if type(x) == X: # If X were a factory class it wouldn't make sense to call __init__() on it. | |
x.__init__() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment