Created
October 30, 2014 09:24
-
-
Save chuanwang66/2bfe5e055281910f6663 to your computer and use it in GitHub Desktop.
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
为了感知到Python类实例的生成,你可以在运行时去做,但是下面这种方式可以让你在编写代码时候实现这个需求: | |
class RegistryMetaClass(type): | |
registry = [] | |
def __new__(cls, clsname, bases, attrs): | |
newclass = super(RegistryMetaClass, cls).__new__(cls, clsname, bases, attrs) | |
RegistryMetaClass.registry.append(newclass()) | |
return newclass | |
class MyClass(object): | |
__metaclass__ = RegistryMetaClass | |
... | |
这样一来,每当生成了MyClass实例,就会被追加到RegistryMetaClass.registry这个list中。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment