In order to search all of the People
objects, you have to have all of the People
objects.
But that implies you shouldn't have them in a bunch of separate variables in the first place, but in some collection, like a list.
Then, get_nonage
can take that list.
While we're at it, there's no reason for get_nonage
to be a method. It's not something that a People
instance does, it's something you do to a bunch of People
instances.
So:
class People:
# ...
def get_nonage(people):
nonage = {person.uid: person.age for person in people if person.age<18}
print(nonage)
people = [
People(1, 11),
People(2, 20),
People(3, 35)
]
get_nonage(people)
In a comment, you ask:
Can I just know the class is People, then use some method of People to directly get all data of its objects
What method would that be? You haven't written one. A class normally doesn't know all of its instances.
Of course if you really want it to, you can make a class record its instances in a class attribute. (A normal instance, like age
, has a separate value for each instance. A class attribute has a single value shared by all instances.)
For example:
class People:
all_people = []
def __init__(self, uid, age):
self.uid = uid
self.age = age
self.all_people.append(self)
If you do that, then you can make get_nonage
into a class method—that is, a method meant to be called on the class itself, rather than on an instance. A class method gets the class, cls
, as its first parameter, instead of an instance, self
, and it can only access class attributes, like the all_people
we just created above.
@classmethod
def get_nonage(cls):
nonage = {person.uid: person.age for person in cls.all_people if person.age<18}
print(nonage)
And now, you can call it, without having to pass it anything, because it already knows everything:
people = [
People(1, 11),
People(2, 20),
People(3, 35)
]
People.get_nonage()
However, this is usually not a great design. For example, what if you wanted to delete a person? Previously, you'd just remove them from the list (or, in your original version, reassign p3
to something else). But then People.all_people
won't know you did that; that person will still be there, and still be counted, even though you no longer have any way to access them.