Skip to content Skip to sidebar Skip to footer

Initialising Nested Classes In Python

Let's say I want to create a class 'House' that has some attributes of its own, but also has a (nested?) 'Resident' class which has some attributes and has a mandatory attribute 's

Solution 1:

I would break out the Resident class and use a property/setter for .resident

Like this:

classHouse:def__init__(self):
        self.someattribute = <someattribute>
        self._resident = None

    @propertydefresident(self):
        returnself._resident

    @resident.setter
    defresident(self, surname):
        r = Resident(surname)
        self._resident = r

classResident:def__init__(self, surname):
        self.surname = surname

However, if you want .resident to be callable but also want to track the house's residents, you can still break out the Resident class, and use:

classHouse:
    def__init__(self):
        self.someattribute = <someattribute>
        self.residents = []

    defresident(self, surname):
        '''
        Add a resident to the house
        '''
        r = Resident(surname)
        self.residents.append(r)
        return r

classResident:
    def__init__(self, surname):
        self.surname = surname

Post a Comment for "Initialising Nested Classes In Python"