在Python中为对象中的多个变量分配值

时间:2018-08-29 15:14:57

标签: python python-3.x

分配点时是否有办法使代码本身不会重复太多?同样,该代码还没有完成,但是还有很多检查要做。当您第一次分配运行状况点时,可以分配更多的点,然后即使没有剩余要分配的点,它也会要求您分配点,并且“剩余点数”变为负数,直到while循环检查为止,但这是我要进行的工作。将尝试修复自己。

class Player:
     def __init__(self, name, health, strength, defence, luck):
         self.name = name
         self.health = health
         self.strength = strength
         self.defence = defence
         self.luck = luck

def playerSetup():
     optio = Player

     name = input(colored("\nWhat is your name soldier? ", "yellow"))
     optio.name = name  


while points > 0:   

    health = int(input("\nType in your Health: "))
    if points > 0:
        optio.health =  health + optio.health
        points = points - optio.health
        print("Points remaining: ", points)

    strength = int(input("\nType in your Strength: "))
    if points > 0:
        optio.strength = optio.strength + strength
        points = points - optio.strength
        print("Points remaining: ", points)

    defence = int(input("\nType in your Defence: "))
    if points > 0:
        optio.defence = optio.defence + defence
        points = points - optio.defence
        print("Points remaining: ", points)

    luck = int(input("\nType in your Luck: "))
    if points > 0:
        optio.luck = optio.luck + luck
        points = points - optio.luck
        print("Points remaining: ", points)

2 个答案:

答案 0 :(得分:0)

将某些东西重构为函数的最简单方法是弄清楚需要传入的值以及需要返回的值:

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,依此类推,但还不足以引起复制粘贴错误。


如果您想消除这种情况,我认为建立一个值的字典,然后根据该字典构造Player对象会更容易。

假设您使用的是Python 3.7+或CPython 3.6,那么我们可以依靠排序的命令:

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)

答案 1 :(得分:0)

减少代码重复的一种方法是定义属性名称列表,并使用setattr()进行分配:

for attribute in ['health', 'strength', 'defence', 'luck']:
    if points > 0:
        amount = int(input('Type in your %s: ' % attribute))
        setattr(optio, attribute, amount)
        points = points - amount
    else:
        print('No points left for %s' % attribute)