问题描述
所以我试图编写一个函数来实例化一个类。 由于我正在遍历该函数,因此我需要一个条件,以便该函数仅在尚未完成该类的情况下实例化该类(否则,HP将在每个循环中都处于极限状态)。 我尝试过的事情:
class Fighter:
def __init__(self):
self.maxHP = 100
self.HP = self.maxHP
self.attack = 10
def before_fight():
if fighterYOU == None: #this is where I would like a condition that checks if fighterYOU is already instantiated. "None" does not work.
fighterYOU = Fighter()
fighterYOU.update()
fight()
before_fight()
#...program continues
是否可以进行这样的检查?还是应该尝试将实例化移动到不会循环的其他地方?
解决方法
如果我理解正确,那么您将避免重新创建战斗机。为此,只需先将变量设置为None:
class Fighter:
def __init__(self):
self.maxHP = 100
self.HP = self.maxHP
self.attack = 10
def before_fight():
if fighterYOU == None: #this is where I would like a condition that checks if fighterYOU is already instantiated. "None" does not work.
fighterYOU = Fighter()
fighterYOU.update()
fight()
fighterYOU = None # default is None
before_fight()
#...program continues
,
Here是答案。
if isinstance(obj,MyClass):
是您所需要的。