python-3.x - 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
解决方案
除了输入之外,您没有分配任何其他内容,(在这种情况下,属性是一个空字符串 ""
。在您的最小示例中,您有这个构造函数:
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
推荐阅读
- javascript - 如何从其他类获取字体系列?
- c# - SharpDX/Direct2D Atlas 效果 InputRectangle 设置错误的 Vector 值
- graph - 如何可视化神经网络
- python - 如何阅读“-”字符?
- file-io - 如何更改 RTF 表格行高
- r - 使用 randomForest() 命令创建循环
- python - How to dynamically control multiple Listboxes simultaneously in tkinter?
- angular - Angular 11 DI 用于动态编译的组件
- amazon-web-services - 我正在部署一个 awscloudformaton 模板来自动与 Active Directory 中的用户一起管理 Amazon Workspaces 生命周期
- javascript - 有没有办法通过单击按钮从数组中删除组件?