Python中两个对象组合的属性
我对Python中的面向对象编程(OOP)还比较陌生。在我的程序里,有两种类型的类:
class Character:
... etc. ...
[Character1
和Character2
是这个类的实例]
还有
class Room:
... etc. ...
[Room1
和Room2
是这个类的实例]
我想为每个Character
和Room
设置一个变量pos
,这样就能为这两个类的每种组合都有一个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 个回答
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)
2
最简单的方法是使用一个字典来查找:
positions = {
(character1, room1): (10, 4),
(character2, room1): (6, 10),
...
}
然后你可以这样查找位置:
pos = positions[characterX, roomY]
另外,有个小提示可能对你有帮助,除非你只用Python 3,否则总是要从对象(object)派生你的类:
class Character(object):
...
3
你可能想要把你的角色和房间的实例放在一个元组里,然后用这个元组作为字典的键,来存储位置的值。
d = {}
d[(Character1, Room1)] = (10, 4)
你也可以考虑创建一个角色和房间的集合,这样就可以逐个遍历它们。