Reputation: 33223
THanks for looking into my post. I guess I have a probably a pretty simple doubt by this community standards.. but pardon me if it is too simple. I am trying to learn python. So anyways.. I have an object which can have five attributes. So lets say when i am initializing the class its like this
class Foo:
def __init__ (self, argA = None, argB = None, argC = None, argD = None....)
and somewhere I have this method called get features
def getFeatures(self):
x = [self._argA, self._argB, self._argc... and so on]
so basically I am trying to put all these features into a list. But here is the problem. During initialization, as you can see all the parameters are optional.. but when I do getFeatures, I only want those features which are initialzed Now a naive way is to write a big if else statement but as Scott Myers wrote in is book.. anytime you see yourself writign a code " if object is of type A do something and if object is of type B do something else... then slap your self.." What is a good way to getFeatures whcih contains only the elements which are initialized. Thanks
Upvotes: 1
Views: 344
Reputation: 151
All attributes can be found in __dict__
attribute of an object as a dictionary (keys->attribute names, values->attribute values). You can filter the uninitialized variables by list comprehension and filtering uninitialized attributes:
def get_initialized_attrs(self):
return [elem for elem in self.__dict__.values() if elem != None]
You may also want to gather attributes with a certain type such as string("str"
), integers("int"
) etc.:
def get_initialized_attrs_bytype(self, type_name):
return [elem for elem in self.__dict__.values() \
if elem != None and type(elem).__name__ == type_name]
Upvotes: 3
Reputation: 123632
Keep a dictionary of feature name to boolean enabled/disabled. That's much better than having all these variables floating around.
def __init__(self, **kwargs):
self.features = kwargs
def getFeatures(self):
return {feature for feature, isEnabled in self.features.items() if isEnabled}
Example:
>>> class Foo(object):
... def __init__(self, **kwargs):
... self.features = kwargs
...
... def getFeatures(self):
... return {feature for feature, isEnabled in self.features.items() if isEnabled}
...
>>> x = Foo(red=True, yellow=False, green=True)
>>> x.getFeatures()
set(['green', 'red'])
Upvotes: 5
Reputation: 37177
def getFeatures(self):
return [field for field in (self._argA, ..., self._argE) if field is not None]
Upvotes: 6