0

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 'surname'. A house instance may exist though without any residents. How can create this so that I can eventually do the following?

myhouse = House()
residentX = myhouse.resident('Smith')

Currently I set this up as a nested class but run into trouble when I try and initialise myhouse given that it is requiring a surname at this point for the nested Resident class (which I don't necessarily have at this point)

class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self.resident = self.Resident()

    class Resident:
        def __init__(self, surname):
            self.surname = surname

I know I can restructure the code to not use nested classes and then explicitly tie any resident to a house in my code. However, I would like to use the dot notation here (myhouse.resident) to automatically tie a resident to a house.

Also, I understand that nested classes in python are somewhat frowned upon - I'm open to suggestions on how to do the above in a more pythonic manner.

1 Answer 1

3

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

Like this:

class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self._resident = None

    @property
    def resident(self):
        return self._resident

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

class Resident:
    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:

class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self.residents = []

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

class Resident:
    def __init__(self, surname):
        self.surname = surname
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that second one is what I needed. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.