简体   繁体   English

您可以使用Python为您创建一个可以创建一个类的多个实例的函数吗?

[英]Can you make a function that would create several instances of a class for you in Python?

I'm trying to figure out some OOP stuff with python and I'm running into a few problems. 我试图用python找出一些OOP的东西,但遇到了一些问题。 I'm trying to make a "game" that involves the player walking around a grid of rooms, with each room an instance of the Room class. 我正在尝试制作一个“游戏”,让玩家在房间的网格中走来走去,每个房间都是Room类的一个实例。 If I wanted to make a big grid, instantiating each room would be a pain as I could potentially have to type in the same repetitive coordinate pattern for 64 different rooms, so I wanted to make a function that would do it for me, I'm running into problems figuring out how. 如果我想制作一个大网格,实例化每个房间将很痛苦,因为我可能必须为64个不同的房间键入相同的重复坐标模式,所以我想创建一个可以为我做的函数我遇到了解决方法的问题。 Here's the code I have: 这是我的代码:

class Room(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

def generate_rooms():

    names = [a,b,c,d]
    locations = [[1,1],[1,2],[2,1],[2,2]] #this line could be a few for loops

    for x in range(0,4):
        names[x] = Room(locations[x][0],locations[x][1])

The idea was that this would create 4 Rooms named a, b, c, and d with the coordinates specified in locations. 想法是,这将创建4个名为a,b,c和d的房间,并在位置中指定坐标。 Python won't let me do this because a, b, c, and d aren't defined. Python不允许我这样做,因为未定义a,b,c和d。 In any implementation I've tried I've run into the problem that naming instances needs to be done with variable names, and I wouldn't know how to generate those dynamically. 在任何实现中,我都曾遇到过这样的问题,即需要使用变量名来命名实例,而我不知道如何动态生成它们。

I've searched around a lot and it doesn't really seem like automation of instantiation is really something people would want to do, which confuses me because it seems like it would really make sense in situations like this. 我进行了很多搜索,似乎并没有真正希望人们自动执行实例化自动化,这使我感到困惑,因为在这种情况下它似乎确实有意义。

Any help on how to fix this or on how to accomplish this task in a better way is greatly appreciated! 非常感谢您提供有关如何解决此问题或以更好的方式完成此任务的帮助!

You're very close! 你很亲密! The usual approach is to use a dictionary, and to use the names you want as dictionary keys. 通常的方法是使用字典,并将所需的名称用作字典键。 For example: 例如:

>>> class Room(object):
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...         
>>> rooms = {}
>>> names = ['a', 'b', 'c', 'd']
>>> locations = [[1,1], [1,2], [2,1], [2,2]]
>>> for name, loc in zip(names, locations):
...     rooms[name] = Room(*loc)
...     
>>> rooms
{'a': <__main__.Room object at 0x8a0030c>, 'c': <__main__.Room object at 0x89b01cc>, 'b': <__main__.Room object at 0x89b074c>, 'd': <__main__.Room object at 0x89b02ec>}
>>> rooms['c']
<__main__.Room object at 0x89b01cc>
>>> rooms['c'].x
2
>>> rooms['c'].y
1

This way you can iterate over the rooms in several ways, for example: 这样,您可以通过几种方式遍历整个房间,例如:

>>> for roomname, room in rooms.items():
...     print roomname, room.x, room.y
...     
a 1 1
c 2 1
b 1 2
d 2 2

A few thoughts: 一些想法:

Perhaps It would make sense to have a name-field in the Room-class? 也许在“房间”级别中有一个名称字段会有意义吗?

What's wrong with a = Room(1,1)? = Room(1,1)有什么问题? You can store a in an array later. 您可以稍后将其存储在数组中。 ie declaring the array AFTER you have instantiated the Rooms. 即在实例化房间之后声明数组。

Why do you care about naming at all? 您为什么不关心命名呢? Python doesn't care. Python不在乎。

Automatic instatiation is trivial and usually done with loops and arrays. 自动声明很简单,通常使用循环和数组来完成。 Writing programs that modify/create programs is referred to as metaprogramming and is not trivial. 编写修改/创建程序的程序称为元编程 ,这非易事。

Good luck! 祝好运!

Just minor changes below: 以下是一些小的变化:

class Room(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

def generate_rooms():
    names = [a,b,c,d]        // <-- this line goes crazy, since a,b,c,d is not defined yet
    locations = [[1,1],[1,2],[2,1],[2,2]] 

    for x in range(0,4):     // <-- this part can be improved
        names[x] = Room(locations[x][0],locations[x][1])

    // no return here? then what to generate?

def new_generate_rooms():
    locations = [[1,1],[1,2],[2,1],[2,2]]
    rooms = [Room(loc[0], loc[1]) for loc in locations]
    return rooms

def main():
    rooms = new_generate_rooms()
    for i,room in enumerate(rooms):
        print str(i)+'-th room: ', room.x, room.y

I am feeling that you may need to learn more of the pythonic syntax and idioms. 我觉得您可能需要学习更多的pythonic语法和习惯用法。 Bless. 保佑。

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

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