我似乎不能正确地调用我的方法

2024-09-24 02:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我正在制作一个超级英雄,第一拳就落地了,但是我需要用我的主控键调用我的方法。我被告知它不在正确的地方,我做了这个代码前一段时间,似乎不能得到它现在。你知道吗

我尝试创建一个新方法,结果将其命名为与属性相同的名称。你知道吗

class Superhero:

    def __init__(self, name = "", strengthPts = 0, staminaPts = 0, stylePts = 0, firstPunch = 0):
        self.name = name 
        self.strengthPts = strengthPts
        self.staminaPts = staminaPts
        self.stylePts = stylePts
        self.firstPunch = firstPunch

    def addStrengthPts(self, points):
        self.strengthPts = self.strengthPts + points

    def addstaminaPts(self, points):
        self.staminaPts = self.staminaPts + points

    def addstylePts(self, points):
        self.stylePts = self.stylePts + points

    def firstPunch(self):

        if(self.firstPunch == "-45 Points"):
            print("First Punch!")
        else:
            print("Miss")

def main():

    theHero = theHero("Eternal", "75", "50", "100", "-45 Points")

    print("Name: " + theHero.name)
    print("Strength Points: " + str(theHero.strengthPts))
    print("Stamina Points: " + str(theHero.staminaPts))
    print("Stle Points: " + str(theHero.stylePts))
    print("-----------------------------")
    print("Hit: " + str(theHero.firstPunch))

main()

预期的结果是多少打孔交易是“-45”,但我得到的是;“UnboundLocalError:局部变量'theHero'在第28行赋值之前引用”,这是我以前从未见过的。你知道吗


Tags: 方法nameselfmaindefpointsprintstr
1条回答
网友
1楼 · 发布于 2024-09-24 02:24:26

如果您在Python中使用class(在您的例子中,它是SuperHero),并且您有一个__init__函数,那么您需要在执行任何其他操作之前初始化它。你知道吗

如果你想创造一个新的英雄,假设他的名字是乔希,你需要这样做:

josh = SuperHero("Eternal", "75", "50", "100","-45 Points")

乔希现在是一个超级英雄的对象,你可以玩:

josh.addstylePts(42)  # Example of using one of the class functions

相关问题 更多 >