简体   繁体   English

我可以使用实例属性调用 class 的实例吗?

[英]Can I call an instance of a class using its instance attribute?

New to python, so the question might not mean what I think it means, apologies if that is the case. python 的新手,所以这个问题可能并不意味着我认为的意思,如果是这种情况,我们深表歉意。

I wrote an adventure game and ran it in a GUI, I have gotten a lot of feedback (including on a deleted question here) that I was using too many global variables and my code could be better organised using classes.我编写了一个冒险游戏并在 GUI 中运行它,我收到了很多反馈(包括这里删除的问题),我使用了太多的全局变量,我的代码可以使用类更好地组织。 So, reading followed, now I am attempting to do what I have read.因此,阅读紧随其后,现在我正在尝试做我所阅读的内容。

I have a class:我有一个 class:

class room:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.location = (self.x, self.y)
    
    #this displays in a GUI window
    def prompt(self):
        write('Another, identical, wood-panelled, four-doored room. What now?')
    
    #this updates a dictionary which maintains current location
    def where(self):
        locale['place'] = self.location
        
    
room1 = room(0, 0)
room2 = room(0, 1)
room3 = room(0, 2)
room4 = room(1, 0)
room5 = room(1, 1)
room6 = room(1, 2)

Now I am using a roomfinder function, to produce prompts and update location based on user input in a GUI.现在我正在使用房间查找器 function,根据 GUI 中的用户输入生成提示和更新位置。 Exerpt:摘录:

def roomfinder():
   #if and nested if statements for every room location  
   elif locale['place'] == room3.location:
        if user_input.lower() == 'n':
            messagebox.showinfo(title='Game Over', message='You fall to your doom. There was no room here! \n \n')
            clear_console()
            startroom()
        elif user_input.lower() == 's':
            clear_console()
            room6.where()
            room6.prompt()
        elif user_input.lower() == 'e':
            messagebox.showinfo(title='Game Over', message='You fall to your doom. There was no room here! \n \n')
            clear_console()
            startroom()
        elif user_input.lower() == 'w':
            clear_console()
            room2.where()
            room2.prompt()
        else:
            write('Please enter a valid response')

Now with nested elif statements for 6 rooms, and a similar function for performing a search in each location, this is big and untidy (feedback agreed with my feelings on this).现在有 6 个房间的嵌套 elif 语句,以及用于在每个位置执行搜索的类似 function,这很大而且不整洁(反馈与我的感受一致)。 I am looking for some code that will do something like (obv this is not real code)我正在寻找一些可以执行类似操作的代码(obv 这不是真正的代码)

if user_input.lower() == 'n'
    locale['place'] = ( current +1, current)
    roomX.prompt where roomX = room where location is locale['place']

does such a syntax exist?这样的语法存在吗? Is this possible?这可能吗? Does my question make sense?我的问题有意义吗?

I don't know if I understood your question correctly, but you could write your code like so:我不知道我是否正确理解了您的问题,但您可以这样编写代码:


def write(msg):
    """Fake write function implementation, that only prints message to console."""
    print(msg)


def clear_console(): pass


class messagebox:
    """Fake Messagebox implementation."""
    def showinfo(
        self,
        title='Game Over',
        message='You fall to your doom. There are no rooms here!\n\n',
    ):
        print(title)
        print(message)


class Room:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.location = (self.x, self.y)
    
    def prompt(self):
        """Display message in GUI window."""
        write('Another, identical, wood-panelled, four-doored room. What now?')

    def __eq__(self, other):
        return self.location == other


class Game(dict):
    """Room game class.
    
    Parameters
    ----------
    xrooms: int | list, default=2
        The number, or list of rooms to create in the X-axis, or North/South direction.
    yrooms: int | list, default=3
        The number, or list of rooms to create in the Y-axis, or East/West direction.
    """

    def __init__(self, xrooms=2, yrooms=3):
        xrooms = list(range(xrooms)) if not isinstance(xrooms, list) else xrooms
        yrooms = list(range(yrooms)) if not isinstance(yrooms, list) else yrooms
        rooms = {
            f'room{i+1}': Room(x, y)
            for i, (x, y) in enumerate(zip(xrooms * len(yrooms), yrooms * len(xrooms)))
        }
        super().__init__(rooms)
        self._current_room = Room(0, 0)
        self.gameover = False
    
    def next_input(self):
        """
        Ask the user for the next input.
        
        If there's no room in the chosen direction, set the attribute `gameover`
        to `True`, to indicate the game has ended.
        """
        user_input = input('Select a direction [N, S, W, E]: ').lower()
        xshift, yshift = 0, 0
        if user_input == 'n':    # Move to room North of current room.
            xshift = 1
        elif user_input == 's':  # Move to room South of current room.
            xshift = -1
        elif user_input == 'w':  # Move to room West of current room.
            yshift = -1
        elif user_input == 'e':  # Move to room East of current room.
            yshift = 1
        else:
            write('Please enter a valid response')
            return self.next_input()
        next_room = self._current_room.x + xshift, self._current_room.y + yshift
        clear_console()
        for room_number, room in self.items():
            if room == next_room:
                self._current_room = room
                room.prompt()
                return self.next_input()
        messagebox().showinfo(
            title='Game Over',
            message='You fall to your doom. There are no rooms here!\n\n',
        )
        self.gameover = True


To play the game, you can use a while/loop condition:要玩游戏,您可以使用while/loop条件:


game = Game()
while not game.gameover:
    game.next_input()

# Prints:
#
# Select a direction [N, S, W, E]: N
# Another, identical, wood-panelled, four-doored room. What now?
# Select a direction [N, S, W, E]: S
# Another, identical, wood-panelled, four-doored room. What now?
# Select a direction [N, S, W, E]: N
# Another, identical, wood-panelled, four-doored room. What now?
# Select a direction [N, S, W, E]: 
# Please enter a valid response
# Select a direction [N, S, W, E]: S
# Another, identical, wood-panelled, four-doored room. What now?
# Select a direction [N, S, W, E]: s
# Game Over
# You fall to your doom. There are no rooms here!

Notes笔记

The write , and clear_console functions, as well as the messagebox class are simply dummy versions that I've created to make the code run. writeclear_console函数以及messagebox class 只是我为使代码运行而创建的虚拟版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM