You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python角色子类分配报错修复与代码优化咨询

Python控制台角色游戏报错修复与优化建议

一、报错修复方案

报错核心原因

你遇到的TypeError: talk_warrior() missing 2 required positional arguments: 'person' and 'warrior',本质是三个逻辑错误导致:

  1. talk_warrior等函数错误定义参数,且内部非法使用self(仅类方法可调用self),调用时又未传参;
  2. 子类(warrior/mage/trader)的__init__未正确传递参数给父类,无法继承角色属性;
  3. 职业设置仅赋值类对象,未关联具体角色实例,无法真正修改角色属性。

具体修复步骤

  1. 重构子类继承逻辑
    将子类改为继承父类属性,并在初始化时完成职业专属属性调整,同时把职业专属对话改为子类的talk方法,替代父类方法:
class Warrior(Person):
    def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intelligence):
        super().__init__(name, hp, luck, xp, level, gold, age, location, strength, intelligence)
        self.strength += 15
        self.intelligence = random.randint(0, 5)
    
    def talk(self):
        return f"Hi, name is {self.name}. {self.strength} strength. I am {self.age}. from {self.location}. intelligence? {self.intelligence}"

class Mage(Person):
    def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intelligence):
        super().__init__(name, hp, luck, xp, level, gold, age, location, strength, intelligence)
        self.strength = random.randint(0, 5)
        self.intelligence += 50
    
    def talk(self):
        return f"Hello my name is The Great MAGE {self.name}. I have {self.strength} strength DONT QUESTION MY STRENGTH. I am {self.age} years old. I happened to be from {self.location}. my intelligence also happens to be {self.intelligence} which is superior to everyone else."

class Trader(Person):
    def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intelligence):
        super().__init__(name, hp, luck, xp, level, gold, age, location, strength, intelligence)
        self.gold += 20
    
    def talk(self):
        return f"Hello my name is {self.name}. I have {self.strength} strength. I am {self.age} years old. I am from {self.location}. I am very average and my intelligence is {self.intelligence}"
  1. 修正角色查找函数
    将空值返回逻辑移到循环外,避免遍历第一个角色就终止:
def find_character():
    chara_name = input("enter the name of the character: ")
    for found_chara in all_people:
        if found_chara.name == chara_name:
            print("found \n")
            return found_chara
    return None
  1. 修复职业设置逻辑
    在职业菜单中,将选中角色替换为对应子类实例,保留原角色属性:
def class_menu():
    chara_loop = True   
    while chara_loop:
        option = int(input("1. warrior \n2. mage \n3. trader \n9. change class \n0. exit \n"))
        if option == 1:
            chara = find_character()
            if chara:
                new_chara = Warrior(chara.name, chara.hp, chara.luck, chara.xp, chara.level, chara.gold, chara.age, chara.location, chara.strength, chara.intelligence)
                idx = all_people.index(chara)
                all_people[idx] = new_chara
                print("Class has been set to warrior.")
                print(new_chara.talk())
        elif option == 2:
            chara = find_character()
            if chara:
                new_chara = Mage(chara.name, chara.hp, chara.luck, chara.xp, chara.level, chara.gold, chara.age, chara.location, chara.strength, chara.intelligence)
                idx = all_people.index(chara)
                all_people[idx] = new_chara
                print("Class has been set to mage.")
                print(new_chara.talk())
        elif option == 3:
            chara = find_character()
            if chara:
                new_chara = Trader(chara.name, chara.hp, chara.luck, chara.xp, chara.level, chara.gold, chara.age, chara.location, chara.strength, chara.intelligence)
                idx = all_people.index(chara)
                all_people[idx] = new_chara
                print("Class has been set to trader.")
                print(new_chara.talk())
        elif option == 0:
            print("returning to main menu. :) \n")
            chara_loop = False
            save_data()
        else:
            print("invalid choice")
  1. 修正主菜单的角色信息展示逻辑
    通过判断角色类来调用对应对话方法:
def menu():
    main_loop = True   
    while main_loop:
        option = int(input("1. create character. \n2. character list. \n3. look for a character. \n4. select character class. \n8. view character info. \n9. delete character from list. \n0. exit \n choice: "))
        if option == 1:
            print("you will now create your character!!!")
            create_character()
        elif option == 2:
            for a_person in all_people:
                print(a_person.talk())
        elif option == 3:
            chara = find_character()
            if chara:
                print(chara.talk())
        elif option == 4:
            class_menu()
        elif option == 8:
            chara = find_character()
            if chara:
                print(chara.talk())
            else:
                print("Character not found!")
        elif option == 9:
            chara = find_character()
            if chara:
                all_people.remove(chara)
                print("character removed")
                save_data()
            else:
                print("Character not found!")
        elif option == 0:
            print("bye!!! :)")
            main_loop = False
            save_data()
        else:
            print("invalid choice")

二、代码优化建议

  • 规范命名:遵循PEP8规范,类名用大驼峰(如Person而非person),变量/函数名用小蛇形(如find_character而非findchara),修正拼写错误(intellegence改为intelligence)。
  • 减少全局变量:将all_people改为Person类的类属性,或通过参数传递,避免全局变量带来的维护问题。
  • 异常处理:添加输入验证(如年龄输入非数字时的捕获)、文件读写异常处理:
def load_data():
    global all_people
    try:
        with open("mypeople.pickle","rb") as f:
            all_people = pickle.load(f)
    except FileNotFoundError:
        all_people = []
  • 简化初始化:将Person类的固定默认值(如hp=100、xp=0)设为__init__的默认参数,减少create_character的重复代码。
  • 模块化拆分:后续扩展时,将战斗、旅行等功能拆分为独立模块(如battle.py、travel.py),提升代码可读性。

三、后续扩展建议

  • 旅行功能:给角色添加current_location属性,用字典定义地图节点,实现移动逻辑,随机触发事件(遭遇怪物、NPC交易)。
  • 战斗功能:创建Monster类,包含名称、血量、攻击力等属性,实现战斗循环:角色攻击→怪物反击→判断胜负,胜利后获得经验、金币,经验达标自动升级并提升属性。
  • 物品系统:添加Item类(武器、药水等),角色可携带物品,武器提升攻击力,药水可回血,商人职业可享受交易折扣。

内容的提问来源于stack exchange,提问作者pythonperson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:40:24