我的课上说它没有函数。Python

2024-06-24 11:40:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的课堂世界里:

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' object has no attribute 'enter_room'

我对Stackoverflow、Python、PEP8甚至Python中的类都是新手,所以请对我放松。你知道吗

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

'world' object has no attribute 'isenemy'


Tags: selffalsetrueworldifobjectdef错误
2条回答

首先,你在第七排有个拼写错误。将def enter\ U room与definit对齐

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')

你把意外的凹痕。函数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')

相关问题 更多 >