两个对象组合的Python属性

时间:2014-04-21 17:13:28

标签: python class python-3.x

我对Python中的OOP相当新。在一个程序中,我有两种类型:

class Character:
    ... etc. ...

[Character1Character2就是这种情况的实例]

class Room:
    ... etc. ...

[Room1Room2就是这种情况的实例]

我希望每个posCharacter都有一个变量Room,这样两个类的每个可能组合都有一个属性pos

例如:

Character1 with Room1 --> pos = (10, 4)
Character2 with Room1 --> pos = (6, 10)
Character1 with Room2 --> pos = (3, 12)
Character2 with Room2 --> pos = (7, 5)

是否有一种简单的方法可以为我所描述的类组合创建属性?我浏览过互联网并没有找到办法。

提前致谢。

3 个答案:

答案 0 :(得分:2)

您可能想要创建角色和房间实例的元组,然后使用该元组作为dict的键来存储pos的值。

d = {}  
d[(Character1, Room1)] = (10, 4)

您可能还希望创建一个字符和房间的集合,以允许每个字符和房间的迭代。

答案 1 :(得分:2)

实现这一目标的最简单方法是使用用于查找的字典:

positions = {
  (character1, room1): (10, 4),
  (character2, room1): (6, 10),
  ...
}

然后您可以像这样查找位置:

pos = positions[characterX, roomY]

另外作为您可能感兴趣的旁注,除非您仅使用Python 3,否则始终从对象派生您的类:

class Character(object):
    ...

答案 2 :(得分:1)

听起来你正在考虑这个错误。这就是我过去所做的。

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Coordinate({x},{y})".format(x=self.x, y=self.y)

class Room(object):
    def __init__(self,name):
        self.name = name
        self.contains = list()
    def addPerson(self,person,where):
        self.contains.append((person,where))
        #  maybe use a dict here? I'm not sure your use case

class Character(object):
    def __init__(self,name):
        self.name = name

然后用它来制造人。

Adam = Character("Adam")
Steve = Character("Steve")
LivingRoom = Room("Living Room")
Kitchen = Room("Kitchen")

LivingRoom.addPerson(Adam, Coordinate(10,4))
LivingRoom.addPerson(Steve, Coordinate(6,10))
Kitchen.addPerson(Adam, Coordinate(3,12))
Kitchen.addPerson(Steve, Coordinate(7,5))

然后每个房间都有contains,可以为每个人及其在该房间内的位置进行迭代。

for person,location in LivingRoom.contains: # occupants might have been a better name
    print ("{0.name} is at ({1.x}, {1.y})".format(person,location))
# Adam is at (10, 4)
# Steve is at (6, 10)