Last active
April 24, 2020 00:59
-
-
Save workze/37243e982f410484f66bdaa602a3b01c to your computer and use it in GitHub Desktop.
python meta type abc
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
handlers = {} | |
class CustomMetaclass(type): | |
def __new__(mcs, name, bases, attrs): | |
cls = type.__new__(mcs, name, bases, attrs) | |
for ext in attrs["formats"]: | |
handlers[ext] = cls | |
return cls | |
class Handler(metaclass=CustomMetaclass): | |
formats = [] | |
# common stuff for all kinds of file format handlers | |
class ImageHandler(Handler): | |
formats = ["jpeg", "png"] | |
class AudioHandler(Handler): | |
formats = ["mp3", "wav"] | |
# | |
print(handlers) | |
# {'mp3': __main__.AudioHandler, | |
# 'jpeg': __main__.ImageHandler, | |
# 'png': __main__.ImageHandler, | |
# 'wav': __main__.AudioHandler} | |
python解释器扫描模块,实例化类; | |
实例化类是利用元类实例化; | |
利用type可以实例化一个类; | |
可以干预一个类的创建过程,修改他的元类即可; | |
元类有一个__new__方法, | |
mcs, name, bases, attrs | |
类,类名,父类,类的属性(__dict__) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment