首页 > 解决方案 > How to print class variables in a list

问题描述

So I am very new to coding and started with python, I am trying to build a class in a program that puts together a DnD party by randomising their attributes. So far I can get the program to initialise instances of the party members and just give the user a prompt on how many of the hero's to choose from they would like in their party. My issue is that after setting the lists up and getting everything in place. I am unable to print any of the attributes of the individual heros. Regardless of whether I am calling them from within the lists or if I am directly trying to print them. I have tried using __str__ to create strings of the attributes but I am clearly missing something. Any help would be greatly appreciated.

import random


class Party:

    def __init__(self, name="", race="", alignment="", class_=""):

        self.name = name
        while name == "":
            name = random.choice(names)
            # print(name)
        self.race = race
        while race == "":
            race = random.choice(races)
            # print(race)
        self.alignment = alignment
        while alignment == "":
            alignment = random.choice(alignments)
            # print(alignment)
        self.class_ = class_
        while class_ == "":
            class_ = random.choice(classes)
            # print(class_)
    def character_stats(self):
        return "{} - {} - {} - {}".format(self.name, self.race, self.class_, self.alignment)

Each attribute pulls a random value from a list. My format statement is the latest attempt to get the values of the attributes to print rather than the object/attributes instead. I apologise if any of the terminology is wrong, very very new to this

标签: python-3.xlistclassrandom

解决方案


除了输入之外,您没有分配任何其他内容,(在这种情况下,属性是一个空字符串 ""。在您的最小示例中,您有这个构造函数:

class Party:
    def __init__(self, name=""):
         self.name = name
         while name == "":
             name = random.choice(names)

从 随机分配一个新名称后names,您应该将其分配给,否则当方法完成self时局部变量就会超出范围。__init__此代码段应该可以工作:

class Party:
    def __init__(self, name=""):
        while name == "":
            name = random.choice(names)
        # Now we assign the local variable as 
        # an attribute
        self.name = name

推荐阅读