I have begun to take my first steps in learning python and am trying to start using classes.
I have this simplified version so far:
class ThingsInTheFridge(object):
def __init__(self):
self.milk = False
self.yogurt = False
self.bread = True
self.umbrella = True
There will be about 30 things in my class and each is assigned True or False (I have shortened the list for this question).
What is the most efficient way to assign them?
I have thought about this but it doesn't seem to improve things especially when the list increases in size:
self.milk, self.yogurt = False, False
EDIT:
I perhaps should have mentioned there are other items in the class to (I omitted them because I didn't think it would matter):
class ThingsInTheFridge(object):
def __init__(self):
self.milk = False
self.yogurt = False
self.bread = True
self.umbrella = True
self.bulb = "maker name"
self.shoes = 2
解决方案
If you really care about runtime efficiency, you're almost certainly looking in the wrong place. If initializing your members takes too long (which is very unlikely… but if you profile and find this is the hotspot…), the right answer is to use __slots__, not to change the way you do the initialization.
If you care about programmer efficiency (readability, and to a lesser extent writability), you can always do this:
self.milk = self.yogurt = False
If you want to do things more dynamically, you could do something like this with setattr, but I wouldn't recommend it:
class ThingsInTheFridge(object):
false_things = ('bread', 'umbrella')
true_things = ('milk', 'yogurt')
def __init__(self):
for thing in ThingsInTheFridge.false_things:
setattr(self, thing, False)
for thing in ThingsInTheFridge.true_things:
setattr(self, thing, True)
The reason I wouldn't recommend it is that, if you need to do things dynamically at this level, you also probably need to be dynamic at the access level, which means you really should be using a dict or set, as explained by Lattyware.
You could also go overboard and build yourself a prototype-style OO system on top of the class-style system, or create a metaclass that initializes instances based on class information, etc., but, as the start of this sentence indicates, that would be going overboard.