0

Is it possible to use a parameter in a class as an identification of the object? For example:

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

myobject = simpleclass("Jerry")
myobject2 = simpleclass("Jimmy")

how do I call all objects that have the name of "Jerry"? Is it even possible? Thanks!

5
  • list_of_objs = [myobject, myobject2] jerrys = [obj for obj in list_of_objs if obj.name == "Jerry"] Commented Feb 6, 2019 at 2:53
  • 2
    your init statement is wrong. it should be __init__ Commented Feb 6, 2019 at 2:55
  • If you had a set simples of simpleclass instances, then `Jerrys = {simple.'Jerry' for simple in simples}. However, simpleclass instances are not callable. Commented Feb 6, 2019 at 2:55
  • also, use self as the first arg to member methods Commented Feb 6, 2019 at 2:56
  • Fixed the mistakes, thanks Commented Feb 6, 2019 at 5:22

2 Answers 2

1

Just check if the name attribute is 'Jerry' for each object that you want to check:

objects = [myobject, myobject2, ...]
[obj for obj in objects if obj.name == 'Jerry']
Sign up to request clarification or add additional context in comments.

3 Comments

This seems to be close, I can tweak it to give me the correct list I want by putting it in a separate for function. However, I can't get your snippet to yield anything in the list, it'd be nice if you can find the problem for other people trying to achieve this.
@HasithVattikuti I'm not sure why you can't get it to work. It works fine for me. And it should be no different than a for-loop with the same structure.
🤦‍♂️ I was looking for an ID (integer) in my code but tried to search for a string. Thanks for the help.
1

It sounds like you may want to use a dictionary to map an object's identifier to a list of all objects with the same identifier. Below is an example.

from collections import defaultdict

simpleclass_list_by_name = defaultdict(list)
simpleclass_list_by_name['Jerry'].append(simpleclass('Jerry'))
simpleclass_list_by_name['Jerry'].append(simpleclass('Jerry'))

for name in simpleclass_list_by_name:
    simpleclass_list = simpleclass_by_name[name]
    for sc in simpleclass_list:
        # do something

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.