【问题标题】:Selecting objects that belong to a specific class when iterating through list of objects遍历对象列表时选择属于特定类的对象
【发布时间】:2021-07-19 09:15:35
【问题描述】:

我试图找到一种方法来遍历对象列表并确定对象属于哪个类,一些对象属于父类,一些属于子类。 这就是我所期待的,但不知道如何让它发挥作用。

class example1():
     def __init__(self,attribute1,attribute2,attribute3,etc):
          self.attribute1 = attribute1
          self.attribute2 = attribute2
          *etc...*

class example2(example1):
     def __init__(self,newAttribute1,newAttribute2,newAttribute3,etc):
          self.newAttribute1 = newAttribute1
          self.newAttribute2 = newAttribute2
          *etc...*

*Code to create a list of a mix of both class example1 and example2*

for object in listOfObjects:
     if object *belongs to* example1:
         *do this*
     else:
          *do this instead*

【问题讨论】:

    标签: python object oop


    【解决方案1】:

    您可以使用isinstance 内置函数。对于您的情况,您可以执行以下操作:

    if isinstance(object, example1):
        ...
    else:
        ...
    

    【讨论】:

    • 同时避免使用内置函数作为标识符。在您的情况下:for object in listOfObjectsobject 隐藏了内置标识符 object。您可以在它们后面加上一个下划线,以防止与内置函数发生冲突。
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2014-02-19
    • 2019-03-22
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多