gpt4 book ai didi

python - "if self:"是什么意思?

转载 作者:行者123 更新时间:2023-12-04 14:07:12 24 4
gpt4 key购买 nike

例子:

class Bird:
def __init__(self):
self.sound = "chirp!"

def reproduce_sound(self):
if self:
print(self.sound)

bird = Bird()
bird.reproduce_sound()

if self: 是什么意思? reproduce_sound 函数调用什么都不打印是什么情况?

最佳答案

它检查实例的真值,并且仅在它为 True 时打印。在您的示例中,支票没有做任何有用的事情,并且总是会打印一些东西。您可以覆盖 __bool__ 方法来更改其默认行为。

例如:

class Bird:
...
def __bool__(self):
return bool(self.sound)

然后:

b = Bird()
b.reproduce_sound() # Prints "chirp!"
b.sound = 0 # or any falsy value, such as None or ""
b.reproduce_sound() # Won't print anything because b == False

关于python - "if self:"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67579003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com