python中的键不允许重复_python3:避免在字典中创建重复键

如果您更改一些代码,您可以将所有创建的Unit作为类变量存储在Unit中。工厂方法应该是classmethods,并将自动向其中添加/创建实例。你知道吗class Unit():

UNITS = {} # shared btw. instances

def __init__(self, name, value):

self.name = name

self.value = value

# nicer output

def __repr__(self): return "{} - {}".format(self.name, self.value)

def __str__(self): return repr(self)

# this should be a classmethod instead, depending on your usage you might want to

# raise Errors instead of returning existing instances

def create_new_unit(name, value):

# create if needed, else return the one already in

# does not alter Unit.value if present

u = Unit.UNITS.setdefault(name, Unit(name,value))

if u.value != value:

raise ValueError("Unit '{}' exists with different value".format(name))

else:

return u

# this should be a classmethod instead, depending on your usage you might want to

# raise Errors instead of returning existing instances def add_new_unit(name, value):

# create new unit or alter an existing Unit's value

# you should rename the method accordingly

u = Unit.UNITS.setdefault(name, Unit(name,value))

u.value = value # change it if called again

return Unit.UNITS

unit1 = create_new_unit('reactor1', 1)

unit2 = create_new_unit('reactor2', 2)

all_units = add_new_unit('reactor3', 3)

for u in Unit.UNITS:

print(id(Unit.UNITS[u]),Unit.UNITS[u])

all_units = add_new_unit('reactor3', 4)

for u in Unit.UNITS:

print(id(Unit.UNITS[u]),Unit.UNITS[u])

输出:140125186245968 reactor1 - 1

140125186246024 reactor2 - 2

140125186246080 reactor3 - 3

140125186245968 reactor1 - 1

140125186246024 reactor2 - 2

140125186246080 reactor3 - 4 # changed by add_new_unit

# if create_new_unit(..) same named unit again with different value:

# ValueError: Unit 'reactor2' exists with different value

就我个人而言,我建议不要创建多个实例化新方法的方法。我可能会把“工厂方法”作为@classmethods,而不是放在普通程序中。这样Unit的所有内务处理都由

Unit类本身,您可以将逻辑集中在它所属的位置,而不必在主程序中添加创建的单元。你知道吗

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值