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

问题描述 投票:-1回答:2

分配点时有没有办法,代码不会重复这么多?此外,代码还没有完成,还有更多的检查要做。当你第一次指定健康点时,你可以分配超过指定的数量,然后它会要求你分配点,即使没有剩下要分配,并且“剩余点数”变为负数,直到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)
python python-3.x
2个回答
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)

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.

现在应该更容易改进你需要改进的东西,因为你只需要在一个地方而不是四个地方写它。

还有一些重复 - 你必须两次输入healthHealth一次,等等 - 但不足以引起copypaste错误。


如果你想消除这一点,我认为建立一个值的dict会更容易,然后从那个dict中构造出Player对象。

假设您使用的是Python 3.7+或CPython 3.6,那么我们可以依赖于订购的dicts:

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)
© www.soinside.com 2019 - 2024. All rights reserved.