类变量不能由函数定义

时间:2014-05-08 16:12:45

标签: python function class python-3.4

由于某些原因,无法在class中定义self变量function

功能:

def pickapoo_specialattack(opponent):
    print("PICKAPOO's FLATULENCE BOLTS WAS EFFECTIVE")
    self.damage -= float(self.damage / 20)
    damage_dealt = random.randrange(200, 250)
    defender.health -= damage_dealt
    print("\nPICKAPOO's DAMAGE RATING WAS DECREASED BY 20%")
    print("PICKAPOO's DAMAGE RATING IS NOW {}".format(str(self.damage)))
    return self.damage

类别:

class Deskemon(object):
    def __init__(self, name, health, damage, defense):

        self.base_name = name
        self.base_health = health
        self.base_damage = damage
        self.base_defense = defense

        self.name = self.base_name
        self.health = self.base_health
        self.damage = self.base_damage
        self.defense = self.base_defense

回溯:

Traceback (most recent call last):
  File "DESKEMON PRE ALPHA.py", line 378, in <module>
    Battle(deskemon, Jack)
  File "DESKEMON PRE ALPHA.py", line 168, in Battle
    Deskemon_Attack(D1, D2, special=(random.randrange(1, 100) <= 45))            
  File "DESKEMON PRE ALPHA.py", line 216, in Deskemon_Attack
    pickapoo_specialattack(defender)
  File "DESKEMON PRE ALPHA.py", line 115, in pickapoo_specialattack
    self.damage -= float(self.damage / 20)
NameError: name 'self' is not defined

以下是我的完整代码:http://pastebin.com/8Xn6UCKS

1 个答案:

答案 0 :(得分:2)

那是因为self变量必须明确地给予python中的方法。当你编写它时,你是否期望python能够阅读你的思想,因此它猜测self应该是你的函数根本没有相关的类?

所以要让它受到限制:

  1. self添加到def pickapoo_specialattack(self, opponent)
  2. 的参数列表中
  3. pickapoo_specialattack(opponent)班级
  4. 中移动Deskemon

    进一步研究你的代码,你正在做的事情肯定是错的,因为你正在击败OOP的整个目的!使用类和子类来执行您的目标。

    让我举一个不完整的例子说明我的意思:

    class Deskemon(object):
        def specialattack(self, opponent):
            raise NotImplementedError
    
        …
    
    class Pickapoo(Deskemon):
        def specialattack(self, opponent):
             … # content of the pickapoo_specialattak() function
    
    class Tamosha(Deskemon):
        def specialattack(opponent):
             … # content of the tamosha_specialattak() function
    

    然后:

    def main():
        pickapoo = Pickapoo(…)
        tamosha = Tamosha(…)
    

    而不是猴子修补 Deskemon实例,使用适当的OOP概念并使Deskemon成为所有实例的基类。然后为每个Deskemon对象创建一个专门的实例,这就是你初始化的东西。

    N.B.1:你应该在主函数中初始化所有对象:

    N.B.2:你应该将所有代码放在主函数的末尾:

    def main():
        # init
        pickapoo = Pickapoo(…)
        tamosha = Tamosha(…)
        lilwilly = Lilwilly(…)
        bigbboy = Biggboy(…)
    
        # start up
        print("Welcome to Deskemon Pre-Alpha V1.2".upper())
        …
    
        # play loop
        while True:
            deskemon_selection_menu()
            deskemon_selection_input = input("> ")
            if deskemon_selection_input == "1":
                deskemon = tamosha
            elif deskemon_selection_input == "2":
                deskemon = pickapoo
            elif deskemon_selection_input == "3":
                deskemon = lilwilly
            elif deskemon_selection_input == "4":
                deskemon = biggboi
            else:
                continue
            print("You have selected {} as your Deskemon".upper().format(deskemon))
            break
    
        # shut down
        print("Professor Andrew: Alright Jack, it's time to pick your Deskemon.")
        …
        print("Jack: OI! " + name + "!")
        time.sleep(1)
    
        Battle(deskemon, Jack)
    
    if __name__ == "__main__":
        main()