我的班级说它没有功能。 Python [关闭]

问题描述 投票:0回答:2

在我的课堂上:

class world:
    def __init__(self):
        if self != 'start_room':
            pass
        else: 
            self.isenemy = random.choice([True, False])
            if isenmey == False:
                self.istrap = random.choice([True, False])

        def enter_room(self):
            if self.isenemy:
                fight()
            elif self.istrap:
                trap()
            else:
                print('The room is empty')

当我运行此代码时:

rooms[current_room].enter_room()

我收到一条错误消息:

'world'对象没有'enter_room'属性

我是Stackoverflow,Python,PEP8的新手,甚至是python中的新类,所以对我来说很容易。

编辑:我现在修复了旧问题我有错误:

'世界'对象没有属性'isenemy'

python python-3.x class
2个回答
1
投票

首先,你在第7行有一个拼写错误。将def enter_room与def init对齐

class world:
    def __init__(self):
        if self != 'start_room':
            pass
        else: 
            self.isenemy = random.choice([True, False])
            if isenmey == False:
                self.istrap = random.choice([True, False])

    def enter_room(self):
        if self.isenemy:
            fight()
        elif self.istrap:
            trap()
        else:
            print('The room is empty')

1
投票

你把意想不到的缩进。你的函数enter_room()是在__init()__中定义的。你去:

class world:
    def __init__(self):
        if self != 'start_room':
            pass
        else: 
            self.isenemy = random.choice([True, False])
            if isenmey == False:
                self.istrap = random.choice([True, False])

    def enter_room(self):
        if self.isenemy:
            fight()
        elif self.istrap:
            trap()
        else:
            print('The room is empty')
© www.soinside.com 2019 - 2024. All rights reserved.