如何编写一个class方法来模拟Python中的对象被另一个对象淘汰?
How to write a class method to simulate object being eliminated by another in Python?
我是第一次使用python class,所以如果代码对你们来说太笨拙,请原谅我。
我想使用 python class 创建一个包含《权力的游戏》角色的 class,我在其中编写了一个 "kill" 函数来使一个角色杀死另一个角色,从而将 1 人添加到他的击杀记录(整数),被击杀的角色将从内存中删除,无法再访问。这是我的代码:
import gc
class Character():
population = 0
def __init__(self, name, house, castle):
self.name = name
self.house = house
self.castle = castle
self.kill=0
print('{0} comes to the world of ice and fire!!!'.format(self.name))
Character.population += 1
def __str__(self):
return 'I am {0} of house {1}, I live in {2}.'.format(self.name,
self.house, self.castle)
def __del__(self):
print ('{0} of house {1} has been slain.'.format(self.name, self.house))
Character.population -= 1
# My kill function:
def kill(slayer, slain):
print('{0} of house {1} has slain {2} of house {3}!'.format(slayer.name, slayer.house, slain.name, slain.house))
slayer.kill +=1
while len(gc.get_referrers(slain))!=0:
del slain
c1=Character('Jofferry','Baratheon',"King's landing")
c2=Character('Eddard','stark','Winterfell' )
print('c1 has',len(gc.get_referrers(c1)),'reference(s)')
print('c2 has',len(gc.get_referrers(c2)),'reference(s)')
Character.kill(c1,c2)
一开始我是直接写的
德尔斯兰
在我的 kill 函数结束时,当我 运行 代码时,它给了我这个:
Jofferry comes to the world of ice and fire!!!
Eddard comes to the world of ice and fire!!!
c1 has 1 reference(s)
c2 has 1 reference(s)
Jofferry of house Baratheon has slain Eddard of house stark!
c1 has 1 reference(s)
c2 has 1 reference(s)
这意味着 del 函数根本不起作用。所以我尝试了 gc.get_referrers 函数并写道:
while len(gc.get_referrers(slain))!=0:
del slain
但它给了我:
Jofferry comes to the world of ice and fire!!!
Eddard comes to the world of ice and fire!!!
c1 has 1 reference(s)
c2 has 1 reference(s)
Jofferry of house Baratheon has slain Eddard of house stark!
Traceback (most recent call last):
File "/home/xiasu/Meca3/Python/Whosebug.py", line 37, in
Character.kill(c1,c2)
File "/home/xiasu/Meca3/Python/Whosebug.py", line 27, in kill
while len(gc.get_referrers(slain))!=0:
UnboundLocalError: local variable 'slain' referenced before assignment
我不明白这是什么意思。请帮助我,在此先感谢!
(顺便说一句:在 python 中是否可以定义一个实例变量(例如:在我的例子中是配偶),它也是同一个 class (字符)中的对象?如果是,我该如何初始化它在'init'?)
你不能做你想做的事。你不能 "delete an object from memory"。 del
删除对象的 引用 (例如,名为 slain
的变量)。如果其他对象仍然持有对 "slain" 字符的引用,那是他们的事。你不能破坏他们的引用。
对于您的示例,尚不清楚为什么您仍然需要这样做。您可以在对象上设置一个标志,例如 slain.dead = True
以将角色标记为已死亡。
唯一明智的做法是将其全部包装在 class 中。
class GameOfThrones(object):
def __init__(self, kingdom):
self.kingdom = kingdom
self.population = {}
def create_character(self, *args, **kwargs):
c = Character(*args, **kwargs)
self.population[c.name] = c
def kill_character(self, killer, victim):
self.population[killer].kill(self.population[victim])
del self.population[victim]
class Character(object):
def __init__(self, name, house, castle):
self.name = name
self.house = house
self.castle = castle
self.victims = []
self.alive = True
@property
def kills(self):
return len(self.victims)
def kill(self, other):
other.dies()
self.victims.append(other)
print("{} killed {}".format(self.name, other.name))
def dies(self):
self.alive = False
game = GameOfThrones()
game.create_character("Joffrey", "Baratheon", "King's Landing")
game.create_character("Eddard", "Stark", "Winterfell")
game.kill_character("Eddard", "Joffrey")
也就是说,这只是勉强 "sane." 确实没有什么理由这样做。
我是第一次使用python class,所以如果代码对你们来说太笨拙,请原谅我。 我想使用 python class 创建一个包含《权力的游戏》角色的 class,我在其中编写了一个 "kill" 函数来使一个角色杀死另一个角色,从而将 1 人添加到他的击杀记录(整数),被击杀的角色将从内存中删除,无法再访问。这是我的代码:
import gc
class Character():
population = 0
def __init__(self, name, house, castle):
self.name = name
self.house = house
self.castle = castle
self.kill=0
print('{0} comes to the world of ice and fire!!!'.format(self.name))
Character.population += 1
def __str__(self):
return 'I am {0} of house {1}, I live in {2}.'.format(self.name,
self.house, self.castle)
def __del__(self):
print ('{0} of house {1} has been slain.'.format(self.name, self.house))
Character.population -= 1
# My kill function:
def kill(slayer, slain):
print('{0} of house {1} has slain {2} of house {3}!'.format(slayer.name, slayer.house, slain.name, slain.house))
slayer.kill +=1
while len(gc.get_referrers(slain))!=0:
del slain
c1=Character('Jofferry','Baratheon',"King's landing")
c2=Character('Eddard','stark','Winterfell' )
print('c1 has',len(gc.get_referrers(c1)),'reference(s)')
print('c2 has',len(gc.get_referrers(c2)),'reference(s)')
Character.kill(c1,c2)
一开始我是直接写的 德尔斯兰 在我的 kill 函数结束时,当我 运行 代码时,它给了我这个:
Jofferry comes to the world of ice and fire!!!
Eddard comes to the world of ice and fire!!!
c1 has 1 reference(s)
c2 has 1 reference(s)
Jofferry of house Baratheon has slain Eddard of house stark!
c1 has 1 reference(s)
c2 has 1 reference(s)
这意味着 del 函数根本不起作用。所以我尝试了 gc.get_referrers 函数并写道:
while len(gc.get_referrers(slain))!=0:
del slain
但它给了我:
Jofferry comes to the world of ice and fire!!!
Eddard comes to the world of ice and fire!!!
c1 has 1 reference(s)
c2 has 1 reference(s)
Jofferry of house Baratheon has slain Eddard of house stark!
Traceback (most recent call last):
File "/home/xiasu/Meca3/Python/Whosebug.py", line 37, in Character.kill(c1,c2)
File "/home/xiasu/Meca3/Python/Whosebug.py", line 27, in kill while len(gc.get_referrers(slain))!=0:
UnboundLocalError: local variable 'slain' referenced before assignment
我不明白这是什么意思。请帮助我,在此先感谢! (顺便说一句:在 python 中是否可以定义一个实例变量(例如:在我的例子中是配偶),它也是同一个 class (字符)中的对象?如果是,我该如何初始化它在'init'?)
你不能做你想做的事。你不能 "delete an object from memory"。 del
删除对象的 引用 (例如,名为 slain
的变量)。如果其他对象仍然持有对 "slain" 字符的引用,那是他们的事。你不能破坏他们的引用。
对于您的示例,尚不清楚为什么您仍然需要这样做。您可以在对象上设置一个标志,例如 slain.dead = True
以将角色标记为已死亡。
唯一明智的做法是将其全部包装在 class 中。
class GameOfThrones(object):
def __init__(self, kingdom):
self.kingdom = kingdom
self.population = {}
def create_character(self, *args, **kwargs):
c = Character(*args, **kwargs)
self.population[c.name] = c
def kill_character(self, killer, victim):
self.population[killer].kill(self.population[victim])
del self.population[victim]
class Character(object):
def __init__(self, name, house, castle):
self.name = name
self.house = house
self.castle = castle
self.victims = []
self.alive = True
@property
def kills(self):
return len(self.victims)
def kill(self, other):
other.dies()
self.victims.append(other)
print("{} killed {}".format(self.name, other.name))
def dies(self):
self.alive = False
game = GameOfThrones()
game.create_character("Joffrey", "Baratheon", "King's Landing")
game.create_character("Eddard", "Stark", "Winterfell")
game.kill_character("Eddard", "Joffrey")
也就是说,这只是勉强 "sane." 确实没有什么理由这样做。