Возникло исключение: объект AttributeError 'Class' не имеет атрибута 'Method' - PullRequest
0 голосов
/ 17 ноября 2018

У меня есть класс символов с этим полным методом.

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

, когда я пытаюсь вызвать его, я получаю следующую ошибку:

Произошло исключение:AttributeError 'Character' объект не имеет атрибута 'FullName'

Я создал экземпляр класса персонажа под названием player

Вот как я его называю

        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)

Вот полный код для всех документов и классов, NewGame

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 голосов
/ 19 ноября 2018

Хорошо, так что я наконец нашел это.Это было уже в первом опубликованном вами коде, но я подумал, что это просто проблема с форматированием здесь, в 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)

Также обратите внимание, что Inventory является атрибутом объекта, который инициализируется пустым.Для этого вам также необходимо получить к нему доступ с помощью self.Inventory позже в методе ShowInventory.

Последнее, что я обнаружил, было то, что вы создали своих врагов неправильно.Frog, вероятно, должен быть классом Frog, а не второй крысой, и вы можете вызвать init вашего родительского класса с помощью super(CHILD, self).__init__(...).Поэтому я изменил ваши классы противника так, чтобы они выглядели следующим образом:

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 нуждается в значениях, вам нужно дать ему три значения (вы забыли способность, пока я просто дал пустую строку).

Это все, что я нашел до сих пор.

0 голосов
/ 17 ноября 2018

Я предполагаю, что вы делаете это:

player = Player()
player.FullName(player)

И это вызывает проблему

При вызове функции класса нет необходимости передавать объект объекта.class.

self относится к вновь созданному объекту (самому себе), экземпляру которого был вызван метод.

Итак, вызов:

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

Предложение: хотяВы могли бы использовать функцию FullName, достаточно просто использовать переменную.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...