簡體   English   中英

Python類無法執行我的功能

[英]Python Class Won't execute my function

因此,我稍早編寫了此代碼,但在調用時將不使用check_level命令或award命令:

from random import randint

class RPG:
    #Defines parts of your character
    def __init__(self, character_name):
        self.chrn = character_name
        self.exp = 0 #Total Experince points
        self.level = 1 #Total Level
        self.h = 25 #Player Health
        self.expn = 10 #Experience Needed
        self.eh = 10 #Base Enemy Health
        self.set = False #Used to chest enemy status
        self.win = False #Used to check for win

    def set_basic(self): # Sets up the basic enemy.
        if self.eh == 0:
            self.eh = 10

    def check_level(self): # Checks to see if you have enough EXP to level up.
        if self.exp >= self.expn:
            self.level = self.level + 1
            self.exp = 0
            self.expn = self.level * 10
            print('Level has increased to {0}'.format(self.level))


    def check_enemy(self): # Checks to see if enemy's health is equal to 0.
        if self.eh == 0:
            print('You Win')
            self.set == True
            RPG.set_basic(self)
        else:
            print('')

    def award(self): # Awards EXP if enemy is dead.
        if self.set == True:
            self.exp = self.exp + 5
            print ('You gained 5 EXP!')

    def attack(self): #The main character's attack.
        x = randint(1,100)
        if x > 20:
            y = randint(1, self.level * 3)
            self.eh = self.eh - y
            final = ('Enemy took {0} damage'.format(y))
            print(final)
            if self.eh < 0:
                self.eh = 0
            print('Enemy has {0} health left'.format(self.eh))
            print('')
            RPG.check_enemy(self)
            RPG.award(self)
            RPG.check_level(self)
        else:
            print('Miss!')

這個:

RPG.check_enemy(self)
RPG.award(self)
RPG.check_level(self)

應該:

self.check_enemy()
self.award()
self.check_level()

隱含了self參數。

編輯:實際上,您的任何RPG.*(self)函數都應該是self.*() -我看到其中的一些在整個課程中散布。

Samsquanch關於將所有RPG.(self)方法調用更改為self.*()是正確的。 調用方法時,python始終會將實例對象作為第一個參數傳遞。 這樣,您可以避免像以前一樣顯式調用該方法。 您可以查看此鏈接以獲取有關self更多詳細信息。

我測試了您的代碼,看來您的問題出在check_enemy() 您需要將self.set == True更改為self.set = True

新方法應如下所示

def check_enemy(self):
    if self.eh == 0:
        print('You Win')
        self.set = True
        self.set_basic()
    else:
        print('')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM