简体   繁体   English

如何使用For循环在Python字典中的对象上应用isinstance()

[英]How to apply isinstance() on objects in a Python dictionary using a For loop

Is there a way to get aa quick True / False on whether I have any nested objects generated from the ProjectTypeB class from my below code? 有没有一种方法可以让我对以下代码中是否有从ProjectTypeB类生成的嵌套对象进行快速True / False

class Project():
    def __init__(self):
        self.subProjects={}

    def addSubProject(self, child):
        child.parent=child
        self.subProjects[child.name]=child

class ProjectTypeA():
    def __init__(self, name):
        self.name=name

class ProjectTypeB():
    def __init__(self, name):
        self.name=name

#Create instances
a=Project()
a.addSubProject(ProjectTypeA("Project1"))
a.addSubProject(ProjectTypeB("Project2"))

From this, I am trying to find a way to check if any of the objects in a.subProjects are instantiated from the class ProjectTypeB (for example). 由此,我试图找到一种方法来检查a.subProjects中的任何对象是否从类ProjectTypeB实例化(例如)。 I have tried things along the lines of the below but with no luck: 我已经尝试了以下方法,但是没有运气:

class Project():
    #... 

    def ProjectTypeB_Specific(self):
        with p in self.subProjects:
            if isinstance(p, ProjectTypeB):
                # Rest of code...

一种快速的方法是通过any带有生成器表达式的方法:

return any(isinstance(p, ProjectTypeB) for p in self.subProjects)

Yes, iterate over it using a looping construct such as for instead of with . 是的,使用诸如for的循环结构而不是with对其进行迭代。 with is intended for context managers, which have a very different usecase. with用于具有不同用例的上下文管理器。

for p in self.subProjects
    if isinstance(p, ProjectTypeB):
        # rest of code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM