I want to explicitly define a new class object. But how do I specify that I want a list of objects

Question:

Say I have a class of people

class person()
   def __init__(self, fname:str, lname:str):
      self.fname = fname
      self.lname = lname

How do I say that I’m expecting a list of person?

class group()
   def __init__(self, groupName:str, people:person|person[]):
      self.groupName = groupName
      self.people = people

Could I use … people:person|list[person]): ?

Asked By: Just Works

||

Answers:

A list of person objects is list[person] (or typing.List[person], prior to Python 3.9).

Answered By: chepner

Yes, you can use people: list[person] to indicate that the people attribute is expected to be a list of person objects. The | symbol is not used in this case, because you only want to specify a single type, which is a list of person objects.

class group():
   def __init__(self, groupName:str, people:list[person]):
      self.groupName = groupName
      self.people = people

When you use the | symbol, you are indicating that the attribute can store either one type or another. For example, person | list[person] would indicate that the attribute can store either a single person object or a list of person objects.

Answered By: xFranko

You can do

class Person:                                                                                           
    def __init__(self, fname: str, lname: str):                                                         
        self._fname = fname                                                                             
        self._lname = lname                                                                             
                                                                                                        
                                                                                                        
class Group:                                                                                           
    def __init__(self, name: str, people: Person|list[Person]):                                   
        self._name = name                                                                   
        self._people = people

and mypy will be happy. That said, it’s probably a better design to simply have people: list[Person] (i.e. only a list is accepted), and have a 1-item list if only one person is in the group. Otherwise, you may have to implement different member functions for different types (or a bunch of if branches) if those functions use self._people.

Answered By: JustLearning
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.