如何正确地调用类
问题描述:
我是一个Python(和一般编程)新手,我正在尝试使用基于列表的随机房间/遇到一个基于文本的无尽RPG。这个代码(当然)还没有完成,它只是用于测试。请注意,我进口的敌人从另一个.py文件:如何正确地调用类
import Enemies
import random
class Room:
# template definition to define all rooms
def __init__(self, intro):
self.intro = intro
class VsRoom(Room):
# room with an enemy
def __init__(self, enemy):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
class NullRoom(Room):
# empty, boring room
def __init__(self):
super().__init__(intro = "Nothing Interesting here.")
Rooms = [VsRoom, NullRoom] # All future room "types" will go here
def print_room():
# Tells the player which kind of room they are
print("You enter the next room...")
Gen_Room = random.choice(Rooms)
print(Gen_Room.intro)
我想打印室()打印“你在旁边的房间进入...”,随机从列表中挑选一个房间,并打印其介绍,但是当我尝试运行它,我得到这个:
You enter the next room...
[...]
print(Gen_Room.intro)
AttributeError: type object 'NullRoom' has no attribute 'intro'
Process finished with exit code 1
我想学习班的工作和任何帮助会为我是巨大的。我试图尽可能多地遵循PEP8,我也试图找到类似的问题,但没有成功。
答
从我观察你,你选择的敌人的名单,这样你就不会需要输入参数:
class VsRoom(Room):
# room with an enemy
def __init__(self):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
要创建一个实例,你必须做到如下:
{class name}()
所以,你必须改变:
Gen_Room = random.choice(Rooms)
要:
Gen_Room = random.choice(Rooms)()
完整代码:
import Enemies
import random
class Room:
# template definition to define all rooms
def __init__(self, intro):
self.intro = intro
class VsRoom(Room):
# room with an enemy
def __init__(self):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
class NullRoom(Room):
# empty, boring room
def __init__(self):
super().__init__(intro = "Nothing Interesting here.")
Rooms = [VsRoom, NullRoom] # All future room "types" will go here
def print_room():
# Tells the player which kind of room they are
print("You enter the next room...")
Gen_Room = random.choice(Rooms)()
print(Gen_Room.intro)
+0
谢谢,它现在正在工作。我也忘记输入'Enemies.Enemy_List'而不是'Enemy_List'。 – Bernardozomer
是什么Enemy_List'的'的价值,以及您在使用'敌人高清_init __(自我,敌人):'' – eyllanesc
是Enemy_List'一个列表来自另一个称为'Enemies'的.py文件。如下所述,'def_init__(自己,敌人)'中敌人的存在是没有必要的。 – Bernardozomer