Python 自定义类实例化失败:为什么 Button 类无法创建实例?
今天将给大家带来,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
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)
答案:
解决这个问题的关键在于确保 __init__.py 文件存在于 button_game 目录中。__init__.py 文件告诉 python 该目录是一个包,允许从包中导入模块。
要在 button_game 目录中创建 __init__.py 文件:
- 打开一个文本编辑器。
- 在 button_game 目录下创建新文件。
- 将文件命名为 __init__.py(确保文件名中包含两个下划线)。
- 保存文件。
在创建一个 __init__.py 文件后,就可以成功导入 button 类并实例化它。
好了,本文到此结束,带大家了解了《Python 自定义类实例化失败:为什么 Button 类无法创建实例?》,希望本文对你有所帮助!关注公众号,给大家分享更多文章知识!