python布尔类型运算_Python中对象布尔值的计算

python: 在布尔上下文中计算对象

每个对象都可以在布尔上下中被计算,如if或while语句。下面示例将演示对象是True或False的规则。

没有__bool__()和__len__()的对象为True

class Foo():

pass

foo = Foo()

if foo:

print("It's true")

else:

print("well, it's false")

bool()决定对象的正确性

如果对象有__bool__方法,__bool__()决定对象的正确性。需要注意的是,Python期望__bool__()返回一个布尔值,否则会抛出异常TypeError

class Foo:

def __init__(self, cnt_true):

self.cnt_true = cnt_true

def __bool__(self):

print('__bool__: cnt_true = ' + str(self.cnt_true))

self.cnt_true -= 1

return self.cnt_true >= 0

foo = Foo(4)

while foo:

print('Still in loop')

print("Loop exited")

# __bool__: cnt_true = 4

# Still in loop

# __bool__: cnt_true = 3

# Still in loop

# __bool__: cnt_true = 2

# Still in loop

# __bool__: cnt_true = 1

# Still in loop

# __bool__: cnt_true = 0

# Loop exited

如果没有__bool__(),则会通过__len__()判断

如果对象没有__bool__()方法,而有__len__()方法,__len__()的返回值决定了对象的正确性。如果返回值为0,对象就是False,否则就是True.需要注意的是,Python期望__len__()返回一个整型。

class Foo:

def __init__(self, cnt_true):

self.cnt_true = cnt_true

def __len__(self):

print("__len__: cnt_true = " + str(self.cnt_true))

self.cnt_true -= 1

return self.cnt_true

foo = Foo(4)

while foo:

print('Still in loop')

print("Loop exited")

# __len__: cnt_true = 4

# Still in loop

# __len__: cnt_true = 3

# Still in loop

# __len__: cnt_true = 2

# Still in loop

# __len__: cnt_true = 1

# Loop exited

bool()的优先级高于__len__()

class Foo:

def __init__(self, cnt_true):

self.cnt_true = cnt_true

def __bool__(self):

print('__bool__: cnt_true = ' + str(self.cnt_true))

self.cnt_true -= 1

return self.cnt_true >= 0

def __len__(self):

print("__len__: cnt_true = " + str(self.cnt_true))

self.cnt_true -= 1

return self.cnt_true

foo = Foo(4)

while foo:

print('Still in loop')

print("Loop exited")

# __bool__: cnt_true = 4

# Still in loop

# __bool__: cnt_true = 3

# Still in loop

# __bool__: cnt_true = 2

# Still in loop

# __bool__: cnt_true = 1

# Still in loop

# __bool__: cnt_true = 0

# Loop exited

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值