3

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.

0

1 Answer 1

2

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)) 
Sign up to request clarification or add additional context in comments.

3 Comments

I've edited my question to provide a little more context, and I also proposed an edit to your answer because people is no longer an argument of the constructor in your example. Thanks!
@DimitriCoukos: Thanks, I forgot to remove those lines. One thing to note: you have no error protection -- if you have a house that doesn't allow pets and a HouseThings.pets is passed in... the house now has pets.
Ahhh yes, luckily my class is meant to eventually have all of the data types.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.