我如何修复我的代码,以便它可以 print() 输出我想要的结果?

How Do I Fix My Code So It Can print() Out The Results I Want?

注意:我不是要你重新编写我的代码,我是在寻找可以帮助我改进此代码的提示和站点链接。如果你想修复代码,我也会接受你的答案。

我正在尝试了解 class 的工作原理,但我真的很难理解。我制作了一个名为 Statclass,其中包含给定用户的所有统计信息。用户的所有统计数据为 name, level, totexp and role。每个 role 有 3 个统计数据(它应该有三个,但是,我的代码搞砸了),health, attack, and defense。这是主要代码(不工作):

class Stat():
    def __init__(self, name, level, totexp, role, health, attack, defense):
        self.name = Name
        self.level = 1
        self.totexp = 0
        self.role = Role
        self.health = health
        self.attack = attack
        self.defense = defense
        self.exp = 0
def choose_name():
    while(True):
        Name = input("What is your Dicer's name?:\n").title()
        if(any(Bad_Words in Name.lower() for Bad_Words in [])):
            print("That's an inappropriate name! Try again")
        elif(len(Name) < 3):
            print("That name is too short! Try again.")
        elif(len(Name) > 16):
            print("That name is too long! Try again.")
        else:
            break
def choose_role():
    Roles = {
   'mage':lambda:Role(100, 40, 10), #(Health, Attack, Defense)
   'warrior':lambda:Role(100, 30, 20),
   'gunner':lambda:Role(100, 20, 30),
   'archer':lambda:Role(100, 10, 40)
   }
    while(True):
        Role = input("What role do you want to be?\nChoices:\n1. Mage\n"
                     "2. Warrior\n3. Gunner\n4. Archer\n").title()
        if(Role.lower() in (Roles)):
            return
        else:
            print("That's not a role! Try again.")
self = choose_name()
self = choose_role()

在主代码之后 Results(如标题)或结果代码应该 printStats 根据实例的顺序。这是结果代码:

print("Here is your Dicer's information:\nDicer's name: {0}\n"
      "Level: {1}\nExperience: {2}\nRole: {3}\nRole Stats:\n"
      "Health: {4}\nAttack: {5}\nDefense: {6}".format(self.name, self.level,
                                                      self.totexp, self.role,
                                                      self.health, self.attack,
                                                      self.defense))

当我 运行 代码时出现错误:

Traceback (most recent call last):
  File "python", line 37, in <module>
AttributeError: 'NoneType' object has no attribute 'name'

我想我知道为什么会发生这种情况,但我不知道如何解决它。你能帮我从哪里开始我的代码和修复它的方法吗?这是我想要的结果(对于此示例,名称 = Bob 和角色 = Gunner):

Dicer's name: Bob
Level: 1
Experience: 0
Role: Gunner
Role Stats:
Health: 100
Attack: 20
Defense: 30

我对 post 有点犹豫,因为代码一团糟。但是你说你不想重写你只是想看到你的代码被修复,所以这里是固定的。我已经评论了我更改的所有内容

#renamed stat to player, the point of the object shouldn't be to hold just the stats, should hold all information
#pertaining to the player / dicer
class Dicer():
    #levelm, totalexp, health removed from constructor
    def __init__(self, name, role, health, attack, defense):
        self.name = name #changed Name to name
        self.level = 1
        self.totexp = 0
        self.role = role #changed Role to role
        self.health = health
        self.attack = attack
        self.defense = defense
        self.exp = 0

    #instance function to print the stats of the dicer
    def print_info(self):
        print(
            "Here is your Dicer's information:\nDicer's name: {0}\nLevel: {1}\nExperience: {2}\nRole:"\
            " {3}\nRole Stats:\nHealth: {4}\nAttack: {5}\nDefense: {6}".format(self.name, self.level, self.totexp, self.role, self.health, self.attack, self.defense)
        )
def choose_name():
    while(True):
        Name = input("What is your Dicer's name?:\n").title()
        if(any(Bad_Words in Name.lower() for Bad_Words in [])):
            print("That's an inappropriate name! Try again")
        elif(len(Name) < 3):
            print("That name is too short! Try again.")
        elif(len(Name) > 16):
            print("That name is too long! Try again.")
        else:
            #you have to return the name so you can use it later
            return Name

def choose_role():
    #removed all the lambdas here
    Roles = {
   'mage': (100, 40, 10), #(Health, Attack, Defense)
   'warrior': (100, 30, 20),
   'gunner': (100, 20, 30),
   'archer': (100, 10, 40)
   }

    while(True):
        Role = input("What role do you want to be?\nChoices:\n1. Mage\n2. Warrior\n3. Gunner\n4. Archer\n").title()
        if(Role.lower() in (Roles)):
            #don't just return None, return the name of the role and it's 3-tuple stats
            #returning the role and it's stats from a function is not the best way to do this
            return Role, Roles[Role.lower()]
        else:
            print("That's not a role! Try again.")

dicer_name = choose_name()
dicer_role_name, dicer_role_stats = choose_role()

#create a dicer using the stats returned from chose_role() function
mainDicer = Dicer(dicer_name, dicer_role_name, dicer_role_stats[0], dicer_role_stats[1], dicer_role_stats[2])
mainDicer.print_info()

如果从头开始编写,我会这样做

class Dicer():
    def __init__(self, name, role, statTuple):
        self.name = name
        self.level = 1
        self.xp = 0
        self.health = statTuple[0]
        self.attack = statTuple[1]
        self.defense = statTuple[2]

    def print_stats(self):
        print("Name", self.name)
        print("Level", self.level)
        print("XP", self.xp)
        print("Health", self.health)
        print("Attack", self.attack)
        print("Defense", self.defense)


roles = {
    #health, attack defense
    "mage" : (100, 40, 10),
    "warrior" : (100, 30, 20),
    "gunner" : (100, 20, 30),
    "archer" : (100, 10, 40)
}
name = input("What is your name ")
dicer_role_choice = None
while dicer_role_choice not in roles.keys():
    print("Please select a dicer:")

    #prints each role on a new line, showing all the possible choices
    print("\n".join(roles.keys()))
    dicer_role_choice = input()

mainDicer = Dicer(name, dicer_role_choice, roles[dicer_role_choice])
mainDicer.print_stats()

我在这里修改了我的代码:

代码提供者:Bradley Elko

更新 1 [51 行]

更新 2 [97 行]

更新 3 [127 行]

更新 4 [148 行]


class Char():
    def __init__(self):
        self.name = ""
        self.role = ""
        self.health = 0
        self.health_now = 0
        self.health_gained = 0
        self.attack = 0
        self.defense = 0
        self.glob()
        self.add_name()
        self.add_role()
        self.print_info()
        self.menu()
    def glob(self):
        global Level, TotXp, Xp, Info, Points
        Level = 1
        Points = 15
        TotXp = 0
        Xp = 0
        Info = "Not Filled In Yet"
    def print_info(self):
        print("\nYour Character's Stats:")
        print("Your character's name is: {0}".format(self.name))
        print("Your character is level: {0}".format(Level))
        print("You have {0} Level Points\n".format(Points))
        print("Your Role Stats:")
        print("Your character's role is: {0}\nYour character's health is: {1}\nYour character's attack is: {2}\nYour character's defense is: {3}".format(self.role, self.health, self.attack, self.defense))
        print("\nIntroduction To Game:\n{0}".format(Info))
    def add_name(self):
        while(True):
            Name = input("What's your character's name?\n")
            if(len(Name) < 3):
                print("That name is too short!")
            elif(len(Name) > 20):
                print("That name is too long!")
            elif(any(bad_word in Name.lower() for bad_word in ['fuck'])):
                print("That name is inappropriate!")
            else:
                self.name += Name
                break
    def add_role(self):
        global Role
        Roles = {
        "Marksman": (100, 50, 30),
        "Melee":(100, 40, 40),
        "Mage":(100, 30, 50)
        }
        while(True):
            Role = input("\nWhat's your characters role?\nChoices:\n1. Marksman\n2. Melee\n3. Mage\n").title()
            if(Role not in ['Marksman', 'Melee', 'Mage']):
                print("That's not a role!")
            else:
                self.role += Role
                self.health += Roles[Role][0]
                self.health_now += Roles[Role][0]
                self.attack += Roles[Role][1]
                self.defense += Roles[Role][2]
                break
    def menu(self):
        global Choice
        print("\nMenu\nWelcome to the menu! Here is where you will be staying in between fights, regaining health, and using the shop.\n")
        while(True):
            Choice = input("Where do you want to go?\n1. Shop\n2. Fight\n3. Sleep\n4. Role Stats\n5. Char Stats\n").lower()
            if(Choice == "shop"):
                return self.shop()
            elif(Choice == "fight"):
                print("Needing updating!")
                break
            elif(Choice == "sleep"):
                self.sleeping()
                break
            elif(Choice == "role stats"):
                return self.role_stats()
            elif(Choice == "char stats"):
                return self.char_stats()
            else:
                print("That's not an option!")
    def menu_two(self):
        global Choice
        print("\nMenu\nWelcome back to the menu!")
        while(True):
            Choice = input("Where do you want to go next?\n1. Shop\n2. Fight\n3. Sleep\n4. Role Stats\n5. Char Stats\n").lower()
            if(Choice == "shop"):
                return self.shop()
            elif(Choice == "fight"):
                print("Needing updating!")
                break
            elif(Choice == "sleep"):
                self.sleeping()
                break
            elif(Choice == "role stats"):
                return self.role_stats()
            elif(Choice == "char stats"):
                return self.char_stats()
            else:
                print("That's not an option!")
    def role_stats(self):
        global Choice
        if(Choice == "role stats"):
            print("\nRole Stats:\nRole: {0}\nHealth: {1}\nAttack: {2}\nDefense: {3}\n".format(self.role, self.health, self.attack, self.defense))
            return self.menu_two()
    def shop(self):
        while(True):
            Buy = input("\nWelcome to the shop! Here is were you spend your level points. What do you want to purchase?\nChoices:\n1. Abilities\n2. Weapons\n3. Stat Points\n4. Nothing\n").lower()
            if(Buy == "abilities"):
                print("\nYou selected 'Abilities'.")
                break
            elif(Buy == "weapon"):
                print("\nYou selected 'Weapons'.")
                break
            elif(Buy == "stat points"):
                print("\nYou selected 'Stat Points'.")
                break
            elif(Buy == "nothing"):
                print("\nReturning to menu...")
                return self.menu_two()
            else:
                print("\nThat is not an option!")
    def char_stats(self):
        global Choice
        if(Choice == "char stats"):
            print("\nYour Character's Stats:")
            print("Username: {0}".format(self.name))
            print("Level: {0}".format(Level))
            print("Level Points: {0}".format(Points))
            return self.menu_two()
    def sleeping(self):
        global Choice
        import time
        if(Choice == "sleep" and self.health_now >= self.health):
            print("\nYour health is full and so you don't need to sleep. Returning to menu.")
            return self.menu_two()
        elif(Choice =="sleep" and self.health_now < self.health):
            print("\nYou are sleeping to regain health. This doubles your characters health regeneration! Please wait patently as your character sleeps to regain health faster.")
            for i in range(1, 1801):
                time.sleep(1)
                if(i in [60,120,180,240,300,360,420,480,540,600,660,720,780,840,900,960,1020,1080,1140,1200,1260,1320,1380,1440,1500,1560,1620,1680,1740,1800]):
                    self.health_gained += 10
                    self.health_now += 10
                    if(self.health_now < self.health):
                        print("\nYou're still healing. You've regained %d health!\nCurrent health:\nHealth: %d/%d" % (self.health_gained, self.health_now, self.health))
                    else:
                        print("\nYou're done healing! You've regained %d health!\nCurrent health:\nHealth: %d/%d" % (self.health_gained - (self.health_now - self.health), self.health, self.health))
                        print("\nYou woke up from your healing nap. Returning to menu.")
                        return self.menu_two()
                    self.health_gained -= 10
MyChar = Char()

更新 1 日期 [6/10/2016]

更新 2 日期 [6/10/2016]

更新 3 日期 [6/11/2016]

更新 4 日期 [6/14/2016]

Link 1: https://repl.it/C0gh/46

Link 2: https://repl.it/C0gh/60

Link3:https://repl.it/C0gh/79