python怎么定义一个变量_在Python中定义类时,如何为一个值分配多个变量?

1586010002-jmsa.png

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值