首页 > 解决方案 > 如何定义这个 Superhero 类,然后创建/使用它的实例

问题描述

我是 Python 新手,在这里非常努力地理解这个问题。我问了一个先前的问题,得到了几个答案,尝试使用每种解决方案,但都没有奏效。如果可以的话请帮忙!

***我需要在我的问题中添加更多文本才能发布,因此请忽略此区域。lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ***

错误信息

Please enter your Super Hero name: 
>PleaseHelpMan
Traceback (most recent call last):
  File "/Users/colinbarclay/Desktop/NEW VERSION of SuperHero Classes..py", line 39, in <module>
    hero = Superhero(superName, power, braun, brains, stamina, wisdom, constitution, dexterity, speed)
TypeError: Superhero() takes no arguments
>>> 

代码

#Importing Random Module

import random

#create Superhero class

class Superhero():
    #initializing our class and setting its atrributes
    def _init_(self,superName, power, braun, brains, stamina, wisdom, constitution, dexterity, speed):
        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

print("Please enter your Super Hero name: ")

# assigning a value to superName using the user's input
superName = input('>')

# adding random values to each

power = random.randint(1,20)
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)


# creating the super hero object
hero = Superhero(superName, power, braun, brains, stamina, wisdom, constitution, dexterity, speed)

# 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("")

标签: python

解决方案


_init_应该有两组下划线,而不是一组。所以,应该是__init__ https://www.w3schools.com/python/python_classes.asp


推荐阅读