Skip to content

Instantly share code, notes, and snippets.

@chuanwang66
Created October 30, 2014 09:24
Show Gist options
  • Save chuanwang66/2bfe5e055281910f6663 to your computer and use it in GitHub Desktop.
Save chuanwang66/2bfe5e055281910f6663 to your computer and use it in GitHub Desktop.
为了感知到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