我是Python新手。在来到这里询问之前,我已经搜索了几个小时来了解为什么会发生这种情况。请帮助我了解如何正确使用类/对象。提前感谢您的帮助和耐心
这里是错误
第46行,在
打印(“大脑:”,英雄。大脑)
AttributeError:“超级英雄”对象没有“大脑”属性
#Importing Random Module
import random
#create Superhero class
class Superhero():
#initializing our class and setting its atrributes
def _init_(self):
self.superName = superName
self.power = power
self.braun = braun
self.brains = brains
self.stamina = stamina
self.wisdom = wisdom
self.constitution = constitution
self.dexterity = dexterity
self.speed = speed
# adding random values to each
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)
print("Please enter your Super Hero name: ")
# creating the super hero object
hero = Superhero()
# assigning a value to superName using the user's input
hero.superName = input('>')
# print the result of the created object, including its parameters
print("Your name is %s. " % (hero.superName))
print("Your new stats are: ")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed: ", hero.speed)
print("")
可以肯定的是,这是你的全部代码吗?因为这里的问题很简单。您忘记将参数添加到类构造函数中。您为统计数据分配了随机数,但它们超出了对象范围,这意味着您的超级英雄不会访问这些变量,除非您将它们作为参数传递给构造函数
有两种方法可以解决这个问题:
A)将它们作为参数传递到构造函数中,因此
然后你可以打印你想要的任何东西
B)由于您的统计数据都是随机的,您可以告诉构造函数将它们分配给随机数,这会将代码缩短几行,但在创建对象时不允许您分配自己的统计数据,如下所示:
你需要告诉超级英雄英雄英雄的属性是什么。在类之外定义它们只会创建与类具有0关系的变量。以下是我的建议:
然后,您可以打印指定给刚刚创建的对象“英雄”的属性:
相关问题 更多 >
编程相关推荐