如何正确调用课程

时间:2017-04-15 03:37:55

标签: python python-3.x

我是一个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,我也试图找到类似的问题,但没有成功。

1 个答案:

答案 0 :(得分:0)

从我观察到你有一个你选择敌人的位置列表,所以你不需要输入该参数:

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)