区分类的实例

2024-04-30 02:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python完全陌生。遵循本指南:http://roguebasin.roguelikedevelopment.org/index.php/Complete_Roguelike_Tutorial,_using_python%2Blibtcod

我有一个简单的问题:当所有的怪物都在这里创建时,python如何区分类的每个实例?据我所知,所有的实例都被命名为“怪物”。在

def place_objects(room):
#choose random number of monsters
num_monsters = libtcod.random_get_int(0, 0, MAX_ROOM_MONSTERS)

for i in range(num_monsters):
    #choose random spot for this monster
    x = libtcod.random_get_int(0, room.x1, room.x2)
    y = libtcod.random_get_int(0, room.y1, room.y2)

    #only place it if the tile is not blocked
    if not is_blocked(x, y):
        if libtcod.random_get_int(0, 0, 100) < 80:  #80% chance of getting an orc
            #create an orc
            fighter_component = Fighter(hp=10, defense=0, power=3, death_function=monster_death)
            ai_component = BasicMonster()

            monster = Object(x, y, 'o', 'orc', libtcod.desaturated_green,
                blocks=True, fighter=fighter_component, ai=ai_component)
        else:
            #create a troll
            fighter_component = Fighter(hp=16, defense=1, power=4, death_function=monster_death)
            ai_component = BasicMonster()

            monster = Object(x, y, 'T', 'troll', libtcod.darker_green,
                blocks=True, fighter=fighter_component, ai=ai_component)

        objects.append(monster)

Tags: 实例getifrandomaicomponentintroom
3条回答

创建一个类的不同的相同实例会产生不同的对象,这些对象具有不同的id。在

>>> class A(object):
...   pass
... 
>>> 
>>> x = A()
>>> y = A()
>>> z = A()
>>> x
<__main__.A object at 0x10049dbd0>
>>> y
<__main__.A object at 0x10049db90>
>>> z
<__main__.A object at 0x10049dc10>
>>> x == y
False
>>> 

还有不同的哈希码

^{pr2}$

Python(CPython)使用引用计数来跟踪对象。在

这一行创建一个对象并将其绑定到一个名称。在

foo = MyObject()

对象现在被一个实体(名称foo)引用,因此它的引用计数是1。在

创建新引用时,计数将增加。删除引用时,计数将减少。在

^{pr2}$

这创建了一个新的引用,所以现在它是2。在

现在假设所有这些都在函数中:

def test():
    foo = MyObject()
    baz = foo

函数执行完毕后,它的所有局部变量都将被删除。这意味着它们停止引用对象,计数就会下降。在这种情况下,计数将达到0,并且MyObject实例将从内存中释放。在

要使对象保持活动,必须保持对它们的引用。如果没有引用,则对象本身很可能已经不存在。

这就是为什么你的代码收集了一个名为objectsobjects.append(monster))的列表中的所有怪物。一个列表将增加它所包含的每个对象的计数,因此当你将“怪物”的名称重新绑定到另一个实例时,上一个实例将不会被删除。在

你唯一缺少的是:

objects = []

在您的功能开始时,以及:

return objects

最后。在

每个对象存储在不同的内存位置。这就是你的区别。在

使用内置函数id()

id(object) 
Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

文件还说

CPython implementation detail: This is the address of the object in memory.

示例:

^{pr2}$

相关问题 更多 >