【问题标题】:Why is 'not' not working when used with a dictionary? [closed]为什么“不”在与字典一起使用时不起作用? [关闭]
【发布时间】:2016-04-18 17:02:53
【问题描述】:
class Enemy(object):
    def __init__(self, name, hp, damage):
       self.name = name
       self.hp = hp
       self.damage = damage

    def is_alive(self):
       return self.hp > 0

enemies = {}

enemies['dog'] = Enemy("Dog", 20, 5)

if enemies['dog'].is_alive:
   print("Woof, Woof!")

enemies['dog'].hp = 0

print(enemies['dog'].hp)

if not enemies['dog'].is_alive:
   print("The dog is dead")

如上所示,我创建了一个类,该类具有检查其中一个变量的数量的函数。当我运行它时,它可以工作,但是,当它为 0 时使用“不”让它打印时,它不打印任何东西,即使我将变量更改为 0。我通过打印 HP 来检查它,改了之后果然改了。

是否有人可以告诉我为什么它不打印?我曾尝试寻找答案,但找不到任何东西。请帮忙!

【问题讨论】:

标签: python class python-3.x if-statement logical-operators


【解决方案1】:

is_alive 是一个不是None、空字符串、0[](,) 等的函数,因此在 if 语句中使用时,它的计算结果为 True

>>> func = lambda: False
>>> if func:
...     print("ehehe")
ehehe

>>> if func():
...     print("ehehe")

你应该调用函数来获取返回值:

>>> if enemies['dog'].is_alive():
...     print("Woof, Woof!")

顺便说一句,调用方法时可以使用@property装饰器去掉括号:

@property
def is_alive(self):
   return self.hp > 0

【讨论】:

  • 所以不调用函数,is_alive 将始终评估为真,不管我是否在它前面加上'not'?那是对的吗?如果是这样,为什么? PS:谢谢!
  • 是的,它总是计算为True。如果你把not放在它前面,它总是会评估为False,就像if (not True):总是被评估为假。
【解决方案2】:

is_alive 是一个方法,所以它需要括号。分配给字典和普通变量没有区别。

class Enemy(object):
    def __init__(self, name, hp, damage):
       self.name = name
       self.hp = hp
       self.damage = damage

    def is_alive(self):
       return self.hp > 0

enemies = {}

enemies['dog'] = Enemy("Dog", 20, 5)
print enemies['dog'].is_alive() 
enemies['dog'].hp = 0
print enemies['dog'].hp 
print enemies['dog'].is_alive()

print

a = Enemy("Dog", 20, 5)
print a.is_alive()
a.hp = 0
print(a.hp)
print a.is_alive()

if not a.is_alive():
    print 'dog is dead'

输出:

True
0
False

True
0
False
dog is dead

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2019-05-19
    • 2019-04-15
    • 2018-02-15
    • 2018-02-15
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多