发生异常:AttributeError'Class'对象没有属性'Method'

时间:2018-11-17 14:57:48

标签: python function class object

我有一个带有全名方法的字符类。

def FullName(self):
            #Name + title
            return '{}'.format(self.name) 

当我尝试调用它时,出现以下错误:

  

发生异常:AttributeError'Character'对象没有属性'FullName'

我已经创建了一个称为玩家的角色类实例

这就是我的称呼

        player.FullName(player)

对于字符类中的所有方法,这都是相同的。我不确定自己在做什么错

class Charcter():
#Setup for charcters
def __init__(self, name, Cclass, damage, damageType, 
health, speed, abilty):
    #Player properties
    self.name = name
    self.Cclass = Cclass
    self.damage = damage
    self.damageType = damageType
    self.health = health
    self.speed = speed
    self.abilty = abilty

    #Invetory list
    Invetory = list()

    def FullName(self):
        #Name + title
        return '{}'.format(self.name)

    def ShowInventory(self):
        #Print every item in inventory
        for Item in Invetory:
            print(Item)

    def Death(self, Enemy):
        print("You have died fighting a " + Enemy.name)
        print("Game over")
        print("Press enter to load from a checkpoint")
        input("")
        #Load check point

    def Battle(self, Enemy):
        print(self.name + " Vs. " + Enemy.name)

这是所有文档和类的完整代码, 新游戏

import StartGame
import GameObjects
#from StartGame import Intro

def overview(userClass, gClasses):
    #convert to int, -1 because lists starts at 0
    userClass = int(userClass) - 1
    print("Class: " + gClasses[userClass][0])
    print("Damage: " + gClasses[userClass][1])
    print("Damage Type: " + gClasses[userClass][2])
    print("Health: " + gClasses[userClass][3])
    print("Speed: " + gClasses[userClass][4])
    print("Abilty: " + gClasses[userClass][5])

def newGame():
    #Class properties - Class name, damage, damageType, health, speed,  abilty
    #Male classes
    barbarian = ["Barbarian", "8", "Sword", "45", "16", "Rage"]
    goblin = ["Goblin", "11", "Dagger", "25", "32", "Pickpocket"]
    mage = ["Mage", "50", "Staff", "75", "16", "Splash"]
    maleClasses= [barbarian, goblin, mage]
    #Female classes
    valkayrie = ["Valkayrie", "94", "2h Axe", "750", "24", "Wirlwind"]
    archer = ["Archer", "7", "Bow", "20", "24", "Long shot"]
    witch = ["Witch", "100", "Staff", "300", "12", "Undead army"]
    femaleClasses = [valkayrie, archer, witch]


    #Users name
    print("What is your Characters name?")
    print("-------------------")
    userName = input("")

    genderIsValid = False
    #While gender isnt set, repeat
    while(genderIsValid == False):
        #Users gender
        print("What is your characters gender? [M/F]")
        print("-------------------")
        userGender = input("").upper()

        if userGender == "M" or userGender == "F":
            #Exit out of loop
            genderIsValid = True
        else:
            #Stay in loop
            print("Please enter a valid statement")
            genderIsValid = False

    #Users class
    print("And what type of warrior are you?")
    #if gender is male
    if userGender == 'M':
        validClass = False
        while validClass == False:
            print("1. A mighty barbarian")
            print("2. A sneaky goblin")
            print("3. A mystical mage")

            print("-------------------")
            userClass = input("")

            if userClass == "1":
                validClass = True

                #overview of class
                overview(userClass, maleClasses)


                validClassConfirm = False
                print("-------------------")
                print("Are you sure? [Y/N]")
                confirm = input("").upper()
                while validClassConfirm == False:
                    if confirm == "Y":
                        validClassConfirm = True
                        #Create instance of the player
                        userClass = int(userClass) - 1
                        player = GameObjects.Character(userName, "Barbarian", "8", "Sword", "45", "16", "Rage")

                        #create class
                    elif confirm == "N":
                        validClass = False
                        validClassConfirm = True
                        #back to selection
                    else:
                        print("Invalid option")

            elif userClass == "2":
                validClass = True

                #overview of class
                overview(userClass, maleClasses)

                validClassConfirm = False
                print("-------------------")
                print("Are you sure? [Y/N]")
                confirm = input("").upper()
                while validClassConfirm == False:
                    if confirm == "Y":
                        validClassConfirm = True
                        #Create instance of the player
                        #Convert and minus 1 cuz list starts at 0
                        userClass = int(userClass) - 1
                        player = GameObjects.Character(userName, ["Goblin", "11", "Dagger", "25", "32", "Pickpocket"])
                        #create class
                    elif confirm == "N":
                        validClass = False
                        validClassConfirm = True
                        #back to selection
                    else:
                        print("Invalid option")

            elif userClass == "3":
                validClass = True

                #overview of class
                overview(userClass, maleClasses)

                validClassConfirm = False
                print("-------------------")
                print("Are you sure? [Y/N]")
                confirm = input("").upper()
                while validClassConfirm == False:
                    if confirm == "Y":
                        validClassConfirm = True
                        #Create instance of the player
                        userClass = int(userClass) - 1
                        player = GameObjects.Character(userName, "Mage", "50", "Staff", "75", "16", "Splash")
                        #create class
                    elif confirm == "N":
                        validClass = False
                        validClassConfirm = True
                        #back to selection
                    else:
                        print("Invalid option")
            else:
                validClass = False
                print("Please enter a valid statment")

            #Give a detail overview with statues using lists

    #if gender is female
    elif userGender == 'F':
        print("1. A warrior valkayrie")
        print("2. A eagle-eyed archer")
        print("3. A fiendish witch")

        print("-------------------")
        userClass = input("")

        if userClass == "1":
                validClass = True

                #overview of class
                overview(userClass, femaleClasses)

                validClassConfirm = False
                print("-------------------")
                print("Are you sure? [Y/N]")
                confirm = input("").upper()
                while validClassConfirm == False:
                    if confirm == "Y":
                        validClassConfirm = True
                        #Create instance of the player
                        player = GameObjects.Character(userName, "Valkayrie", "94", "2h Axe", "750", "24", "Wirlwind")
                        #create class
                    elif confirm == "N":
                        validClass = False
                        validClassConfirm = True
                        #back to selection
                    else:
                        print("Invalid option")


        elif userClass == "2":
            validClass = True

            #overview of class
            overview(userClass, femaleClasses)

            validClassConfirm = False
            print("-------------------")
            print("Are you sure? [Y/N]")
            confirm = input("").upper()
            while validClassConfirm == False:
                if confirm == "Y":
                    validClassConfirm = True
                    #Create instance of the player
                    #Convert and minus 1 cuz list starts at 0
                    userClass = int(userClass) - 1
                    player = GameObjects.Character(userName, "Archer", "7", "Bow", "20", "24", "Long shot")
                    #create class
                elif confirm == "N":
                    validClass = False
                    validClassConfirm = True
                    #back to selection
                else:
                    print("Invalid option")

        elif userClass == "3":
            validClass = True

            #overview of class
            overview(userClass, maleClasses)

            validClassConfirm = False
            print("-------------------")
            print("Are you sure? [Y/N]")
            confirm = input("").upper()
            while validClassConfirm == False:
                if confirm == "Y":
                    validClassConfirm = True
                    #Create instance of the player
                    player = GameObjects.Character(userName, "Witch", "100", "Staff", "300", "12", "Undead army")
                    #create class
                elif confirm == "N":
                    validClass = False
                    validClassConfirm = True
                    #back to selection
                else:
                    print("Invalid option")
        else:
            validClass = False
            print("Please enter a valid statment")

        #Give a detail overview with statues using lists
    else:
        print("Error, restart game")

    print("Press Enter to start the game")    
    print("-------------------")
    userClass = input("")

    print(player)
    StartGame.Intro(player)
    #new function
    #save data



newGame()

GameObjects:

class Character():
    #Setup for charcters
    def __init__(self, name, Cclass, damage, damageType, 
    health, speed, abilty):
        #Player properties
        self.name = name
        self.Cclass = Cclass
        self.damage = damage
        self.damageType = damageType
        self.health = health
        self.speed = speed
        self.abilty = abilty

        def FullName(self):
            #Name + title
            return '{}'.format(self.name)

        def ShowInventory(self):
            #Print every item in inventory
            for Item in Invetory:
                print(Item)

        def Death(self, Enemy):
            print("You have died fighting a " + Enemy.name)
            print("Game over")
            print("Press enter to load from a checkpoint")
            input("")
            #Load check point

        def Battle12(self, Enemy):
            print(self.name + " Vs. " + Enemy.name)



class Item():
    def __init__(self, name, Type, description, value):
        self.name = name
        self.Type = Type
        self.description = description
        self.value = value

        def printItem():
            print("Name: " + name)
            print("Type: " + Type)
            print("Description :" + description)
            print("Value: " + value)

StartGame:

import Enemies
import GameObjects

def Intro(player):
    print(player)
    #print("You better move fast " player.name + " your  village is under attack")
    print("You're village is being swarmed by plagued rats from the east \n and poisonous frogs from the west")
    print("")

    print("Which do you fight")
    print("1. Rats")
    print("2. Frogs")
    print("-------------------")
    choice = input("")

    #if rats
    if(choice == "1"):
        player.Battle12(Enemies.Rat())
        #Battle method           

    elif(choice == "2"):
        pass
        #battlemethod
    else:
        print("Invalid option")

敌人:

class Enemy():
    #Enemies
    def __init__(self, name, damage, health, ability):
        #Enemies properties
        self.name = name
        self.damage = damage
        self.health = health
        #Later 
        self.ability = ability

        def isAlive(self):
            return self.health > 0

class Rat(Enemy):
    def __init__(self):
        super().__init__(name="Rat", damage = 1, health = 2)

class Rat(Enemy):
    def __init__(self):
        super().__init__(name="Frog", damage = 1, health = 2)

2 个答案:

答案 0 :(得分:2)

好,所以我终于找到了。它已经在您发布的第一个代码中了,但是我认为这只是Stackoverflow上此处格式的问题。事实证明,您的整个问题在于缩进。但是让我们一次迈出一步。

因此,在Character类中,方法定义位于 init 内部中。 这就是为什么它们不属于班级的原因,以及后来的播放器不具有这些属性的原因。

因此它必须如下所示:

class Character():
    # Setup for charcters
    def __init__(self, name, Cclass, damage, damageType,
             health, speed, abilty):
        # Player properties
        self.name = name
        self.Cclass = Cclass
        self.damage = damage
        self.damageType = damageType
        self.health = health
        self.speed = speed
        self.abilty = abilty
        self.Inventory = {}

    def FullName(self):
        # Name + title
        return '{}'.format(self.name)

    def ShowInventory(self):
        # Print every item in inventory
        for Item in self.Invetory: ## fixme
            print(Item)

    def Death(self, Enemy):
        print("You have died fighting a " + Enemy.name)
        print("Game over")
        print("Press enter to load from a checkpoint")
        input("")
        # Load check point

    def Battle12(self, Enemy):
        print(self.name + " Vs. " + Enemy.name)

还要注意,库存是对象的属性,该对象初始化为空。因此,您还必须稍后在ShowInventory方法中使用self.Inventory进行访问。

我发现的最后一件事是,您错误地创建了敌人。 青蛙可能应该是青蛙类而不是第二只老鼠,您可以使用super(CHILD, self).__init__(...)来调用父类的初始化。 因此,我将您的Enemy类更改为如下所示:

class Rat(Enemy):
    def __init__(self):
        super(Rat, self).__init__("Rat", 1, 2, "")


class Frog(Enemy):
    def __init__(self):
        super(Frog, self).__init__("Frog", 1, 2, "")

为简洁起见,我只是省略了关键字。另外,如果您的父init需要值,则需要给它三个值(您忘了能力,我现在只给它一个空字符串)。

这就是我到目前为止发现的全部。

答案 1 :(得分:1)

我假设您正在这样做:

player = Player()
player.FullName(player)

这就是问题所在

调用类的函数时,无需传递类的对象。

self指的是新创建的对象(本身),即调用其方法的实例。

所以打电话:

full_name = player.FullName()
print "Full name : {}".format(full_name)

一个建议:尽管可以使用FullName函数,但是使用变量可能就足够了。