Py学习  »  Python

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

Jakob • 7 年前 • 2343 次点击  

在分配点时有没有一种方法,代码不会重复太多? 另外,代码还没有完成,还需要进行更多的检查。当您第一次分配健康点时,您可以分配超过指定的,然后它要求您分配点,即使没有剩余要分配的点,并且在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/Django开发社区
本文地址:http://www.python88.com/topic/38566
文章 [ 2 ]  |  最新文章 7 年前
abarnert
Reply   •   1 楼
abarnert    8 年前

将某个东西重构为函数的最简单方法是找出需要传递的值以及需要返回的值:

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)
John Gordon
Reply   •   2 楼
John Gordon    8 年前

减少代码重复的一种方法是定义属性名列表并使用 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)