Is there a way how to specify scene objects in for loops?

I have this script:

for obj in scene.objects:
   if "prop" in obj:
      obj.doWhatever();

This loops through every object on the scene until it finds those who have the “prop” property.
Can I somehow specify if I want to loop through objects with certain types like Empty or objects with a certain name only?
And if I can specify that, does that help the performance a bit, to loop through just a selected few objects or is there no difference?

for obj in scene.objects:
   if obj.name == 'óbject_name':
      obj.doWhatever()

looping trough this every tic is resource heavy, so what you can do is make a list out of items you going to need at startup

if not __init__ in own:
   #grab all items with a property 'property'. and put it into a list
    own['obj_list'] = [obj for obj in own.scene.objects if 'property' in obj]
    own[__init__] = True

and now you can loop trough own[‘obj_list’]

1 Like

Thank you,
So if I understand correctly. If I set this just once, I can loop through this and it will count just the objects from the list instead of all the objects on the scene.

indeed, but if you add more objects then you need to append it to the list or rebuild the list.

For some reason, the __init__ doesn’t work.
The console shows this:

NameError: name '__init__' is not defined

I was able to define it differently, however.

example got a typo

change

if not __init__ in own:
   #grab all items with a property 'property'. and put it into a list
    own['obj_list'] = [obj for obj in own.scene.objects if 'property' in obj]
    own[__init__] = True

to

if not "__init__" in own:
   #grab all items with a property 'property'. and put it into a list
    own['obj_list'] = [obj for obj in own.scene.objects if 'property' in obj]
    own["__init__"] = True

init needs to be a string in this case

1 Like

Thank you. I was able to make this work with similar commands.
I thought that init had some other function but it was just a property?

__init__ is actually a reserved class method in python, so you really should not use it as a variable and you are just setting yourself up for a lot of pain if you do use it, do to the risk of naming conflicts.

in a python class __init__ if present is the first function to be called

example:

class Test:
   # __init__ called when class is created
   def __init__(self):
     # init the class variables
     self.somevariable = somthing

#create instance of class Test
test = Test()
2 Likes

I see, thank you for the info.