简体   繁体   English

如何使用返回的值在Python中打开类的另一个实例?

[英]How can I use a returned value to open up another instance of a class in Python?

I am on exercise 43 doing some self-directed work in Learn Python The Hard Way . 我正在练习43中,在Learn Python The Hard Way中做一些自我指导的工作。 And I have designed the framework of a game spread out over two python files. 我设计了一个游戏框架,分布在两个python文件中。 The point of the exercise is that each "room" in the game has a different class. 练习的重点是游戏中的每个“房间”都有不同的类。 I have tried a number of things, but I cannot figure out how to use the returned value from their initial choice to advance the user to the proper "room", which is contained within a class. 我已经尝试了很多方法,但是我无法弄清楚如何使用他们最初选择的返回值来将用户提升到包含在类中的适当“房间”。 Any hints or help would be greatly appreciated. 任何提示或帮助将不胜感激。

Apologies for the poor code, I'm just starting out in python, but at my wit's end on this. 为可怜的代码表示歉意,我只是从python开始,但我的智慧就此结束了。

Here is the ex43_engine.py code which I run to start the game. 这是我运行以启动游戏的ex43_engine.py代码。


from ex43_map import *
import ex43_map
import inspect

#Not sure if this part is neccessary, generated list of all the classes (rooms) I imported from ex43_map.py, as I thought they might be needed to form a "map"
class_list = []
for name, obj in inspect.getmembers(ex43_map):
    if inspect.isclass(obj):
        class_list.append(name)

class Engine(object):

    def __init__(self, room):
        self.room = room 


    def play(self):
        # starts the process, this might need to go inside the loop below
        next = self.room      
        start.transportation_choice()

        while True:
            print "\n-------------"
            # I have tried numerous things here to make it work...nothing has

start = StartRoom()
car = CarRoom()
bus = BusRoom()
train = TrainRoom()
airplane = AirplaneRoom()
terminal = TerminalRoom()

a_game = Engine("transportation_choice")
a_game.play()

And here is the ex43_map.py code 这是ex43_map.py代码


from sys import exit
from random import randint

class StartRoom(object):
    def __init__(self):
        pass
    def transportation_choice(self):
        print "\nIt's 6 pm and you have just found out that you need to get to Chicago by tomorrow morning for a meeting"
        print "How will you choose to get there?\n"
        print "Choices: car, bus, train, airplane"
        choice = raw_input("> ")

        if choice == "car":
            return 'CarRoom'

        elif choice == "bus":
            return 'BusRoom'

        elif choice == "train":
            return 'TrainRoom'

        elif choice == "airplane":
            return 'AirplaneRoom'

        else:
            print "Sorry but '%s' wasn't a choice." % choice
            return 'StartRoom'


class CarRoom(object):

    def __init__(self):
        print "Welcome to the CarRoom"

class BusRoom(object):

    def __init__(self):
        print "Welcome to the BusRoom"

class TrainRoom(object):

    def __init__(self):
        print "Welcome to the TrainRoom" 

class AirplaneRoom(object):

    def __init__(self):
        print "Welcome to the AirplaneRoom"

class TerminalRoom(object):

    def __init__(self):
        self.quips = [
            "Oh so sorry you died, you are pretty bad at this.",
            "Too bad, you're dead buddy.",
            "The end is here.",
            "No more playing for you, you're dead."
            ]

    def death(self):
             print self.quips[randint(0, len(self.quips)-1)] # randomly selects one of the quips from 0 to # of items in the list and prints it 
             exit(1)  

Instead of returning a string try returning an object, ie 而不是返回字符串,而是尝试返回一个对象,即

    if choice == "car":
        return CarRoom()
  1. It might be a good idea to make a Room class, and derive your other rooms from it. 创建一个Room类并从中派生其他房间可能是一个好主意。

  2. The Room base class can then have a class variable which automatically keeps track of all instantiated rooms. 然后,Room基类可以具有一个类变量,该变量会自动跟踪所有实例化的房间。

I haven't thoroughly tested the following, but hopefully it will give you some ideas: 我尚未彻底测试以下内容,但希望它能给您一些想法:

# getters.py
try:
    getStr = raw_input   # Python 2.x
except NameError:
    getStr = input       # Python 3.x
getStr.type = str

def typeGetter(dataType):
    def getter(msg):
        while True:
            try:
                return dataType(getStr(msg))
            except ValueError:
                pass
    getter.type = dataType
    return getter

getInt   = typeGetter(int)
getFloat = typeGetter(float)
getBool  = typeGetter(bool)

def getOneOf(*args, **kwargs):
    """Get input until it matches an item in args, then return the item

    @param *args: items to match against
    @param getter: function, input-getter of desired type (defaults to getStr)
    @param prompt: string, input prompt (defaults to '> ')

    Type of items should match type of getter
    """
    argSet = set(args)
    getter = kwargs.get('getter', getStr)
    prompt = kwargs.get('prompt', '> ')

    print('[{0}]'.format(', '.join(args)))
    while True:
        res = getter(prompt)
        if res in argset:
            return res

.

# ex43_rooms.py
import textwrap
import random
import getters

class Room(object):
    # list of instantiated rooms by name
    ROOMS = {}

    @classmethod
    def getroom(cls, name):
        """Return room instance
        If named room does not exist, throws KeyError
        """
        return cls.ROOMS[name]

    def __init__(self, name):
        super(Room,self).__init__()
        self.name = name
        Room.ROOMS[name] = self

    def run(self):
        """Enter the room - what happens?
        Abstract base method (subclasses must override)
        @retval Room instance to continue or None to quit
        """
        raise NotImplementedError()

    def __str__(self):
        return self.name

    def __repr__(self):
        return '{0}({1})'.format(self.__class__.__name__, self.name)

class StartRoom(Room):
    def __init__(self, name):
        super(StartRoom,self).__init__(name)

    def run(self):
        print textwrap.dedent("""
            It's 6 pm and you have just found out that you need to get to Chicago
            by tomorrow morning for a meeting! How will you get there?
        """)
        inp = getters.getOneOf('car','bus','train','airplane')
        return Room.getroom(inp)

class CarRoom(Room):
    def __init__(self,name):
        super(CarRoom,self).__init__(name)

class BusRoom(Room):
    def __init__(self,name):
        super(BusRoom,self).__init__(name)

class TrainRoom(Room):
    def __init__(self,name):
        super(TrainRoom,self).__init__(name)

class PlaneRoom(Room):
    def __init__(self,name):
        super(PlaneRoom,self).__init__(name)

class TerminalRoom(Room):
    def __init__(self,name):
        super(TerminalRoom,self).__init__(name)

    def run(self):
        print(random.choice((
            "Oh so sorry you died, you are pretty bad at this.",
            "Too bad, you're dead buddy.",
            "The end is here.",
            "No more playing for you, you're dead."
        )))
        return None

# create rooms (which registers them with Room)
StartRoom('start')
CarRoom('car')
BusRoom('bus')
TrainRoom('train')
PlaneRoom('airplane')
TerminalRoom('terminal')

.

# ex43.py
from ex43_rooms import Room

def main():
    here = Room.getroom('start')
    while here:
        here = here.run()

if __name__=="__main__":
    main()

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

相关问题 如何在python的另一个应用程序中使用函数返回的值? - How can I use a value returned by a function in another application in python? 在类的实例中,可以使用一个方法返回的值作为调用另一个方法的参数吗 - In an instance of a class, can you use a value returned from a one method, as a parameter for calling another method 如何在python中将实例从一个类切换到另一个类? - How can I switch a instance from one class to another in python? 如何在python中使用来自另一个类的变量? - How can I use variables from another class in python? 如何从 Python 中的另一个类更改变量的值? - How can I change the value of a variable from another class in Python? 如何静态使用类实例? - How can I use class instance statically? 如何使用Python defaultdict将一个值除以另一个? - How can I use a Python defaultdict to divide one value by another? 我如何使用一个变量的值在python中调用另一个变量? - How can i use the value of one variable to call another in python? 如何/我可以使用 python 3 设置一个实例以使用已经为 AWS ec2 制作的实例 - How/Can I set up an instance to use an already made for AWS ec2 using python 3 如何使用Python Class属性作为@Classmethod的默认值? - How can I use a Python Class attribute as a default value for a @Classmethod?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM