将某个东西重构为函数的最简单方法是找出需要传递的值以及需要返回的值:
def spendattr(name, value, points):
spent = int(input(f"\nType in your {name}: ")
if points > 0:
value = value + spent
points = points - spent
print("Points remaining: ", points)
return value, points
然后通常称之为一行:
while points > 0:
optio.health, points = spendattr('Health', optio.health, points)
optio.strength, points = spendattr('Strength', optio.strength, points)
⦠etc.
现在,无论你需要改进什么,都应该更容易改进,因为你只需要在一个地方而不是在四个地方写。
还有一点重复你必须打字
health
两次和
Health
一次,等等,但不足以引起复制粘贴错误。
如果你想消除这一点,我认为建立一个值的dict,然后用这个dict构造player对象会更容易。
假设您使用的是python 3.7+或cpython 3.6,那么我们可以依赖所订购的dict:
def spendattr(name, attrs, points):
spent = int(input(f"\nType in your {name.title()}: ")
if points > 0:
attts[name] = attrs[name] + spent
points = points - spent
print("Points remaining: ", points)
return points
attrs = {'health':0, 'strength':0, â¦}
while points > 0:
for attr in attrs:
points = spendattr(name, attrs, points)
player = Player(name=playername, **attrs)