python 自定义类实例化失败
问题:
在尝试实例化一个自定义类 button 时,遇到 "无法创建实例" 的错误。以下代码来自 button_game 包:
import pygame from button_game.setting import Settings from button_game import game_functions as gf from button_game.button import Button def run_game(): pygame.init() button_setting = Settings() screen = pygame.display.set_mode(button_setting.screen_width, button_setting.screen_height) screen.display.set_caption("按键") button = Button(button_setting, screen) # 这里报错 while True: gf.check_events(button)
答案:
立即学习“Python免费学习笔记(深入)”;
解决这个问题的关键在于确保 __init__.py 文件存在于 button_game 目录中。__init__.py 文件告诉 python 该目录是一个包,允许从包中导入模块。
要在 button_game 目录中创建 __init__.py 文件:
在创建一个 __init__.py 文件后,就可以成功导入 button 类并实例化它。
以上就是Python 自定义类实例化失败:为什么 Button 类无法创建实例?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号