Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass enum type as constructor argument

I am new to python and I would like to pass an enum as an argument to a constructor, within a function.

EDIT: I am working on a program with a class that has to organize different types of data, but most of these data types can be treated the same way. This data won't be all be added at the same time or in a foreseeable order. I would therefore like to keep the same functions, and just change the way the constructor stores the data. Let's consider this simpler example:

Say I have an enum

from enum import Enum, auto

class HouseThing(Enum):
    people = auto()
    pets = auto()
    furniture = auto()

And I have a class House that can contain some or all of those things

class House():

    def __init__(self, address, people = None, pets = None, 
        furniture = None):
        self.address = address, 
        if self.people is not None:
            self.people = people

        etc....

And now I want to have a function that makes new furbished houses, but I want to use a function that could be used for any house:

house_things = HouseThing.furniture

def make_house_with_some_house_things(neighborhood, house_things):
     neighborhood.append(House(house_things.name = house_things.name))

Is there a way to do this without first testing what kind of HouseThing house_things is first? house_things.name passes a string, but I would like it to be able to use it as a keyword.

like image 275
Dimitri Coukos Avatar asked Dec 30 '25 19:12

Dimitri Coukos


1 Answers

I'm not sure exactly what you are trying to achieve here, but for the sake of solving the puzzle:

First, change House to determine what it has been passed:

class House():

    def __init__(self, address, *house_things):
        self.address = address
        for ht in house_things:
            if ht is HouseThings.people:
                self.people = ht
            elif ht is HouseThings.pets:
                self.pets = ht
            elif ht is HouseThings.furniture:
                self.furniture = ht
            else:
                raise ValueError('unknown house thing: %r' % (ht, ))

Then, change make_house_with_some_house_things to just pass the house things it was given:

def make_house_with_some_house_things(neighborhood, house_things):
     neighborhood.append(House(house_things))
like image 99
Ethan Furman Avatar answered Jan 02 '26 08:01

Ethan Furman