栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我可以遍历Python中的类吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我可以遍历Python中的类吗?

如果要遍历 该类 ,则必须定义一个支持迭代的元类。

x.py:

class it(type):    def __iter__(self):        # Wanna iterate over a class? Then ask that class for iterator.        return self.classiter()class Foo:    __metaclass__ = it # We need that meta class...    by_id = {} # Store the stuff here...    def __init__(self, id): # new isntance of class        self.id = id # do we need that?        self.by_id[id] = self # register istance    @classmethod    def classiter(cls): # iterate over class by giving all instances which have been instantiated        return iter(cls.by_id.values())if __name__ == '__main__':    a = Foo(123)    print list(Foo)    del a    print list(Foo)

最终您将看到,删除实例不会对对象本身产生任何影响,因为它保留在

by_id
字典中。您可以使用
weakref
s来应对

import weakref

然后做

by_id = weakref.WeakValueDictionary()

。这样,仅在存在“强”引用的

a
情况下才保留值,例如在这种情况下。在之后
del a
,只有弱引用指向该对象,因此可以对其进行gc’ed。

由于有关

WeakValueDictionary()
s的警告,我建议使用以下命令:

[...]    self.by_id[id] = weakref.ref(self)[...]@classmethoddef classiter(cls):    # return all class instances which are still alive according to their weakref pointing to them    return (i for i in (i() for i in cls.by_id.values()) if i is not None)

看起来有点复杂,但是要确保您得到的是对象而不是

weakref
对象。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611739.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号