"if self:" 的意思是什么?

3

例子:

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函数调用不会打印任何内容?


1
在这个特定的情况下,我认为它总是会打印的。但一般而言,一个类可以重写__bool__方法,以便在所需条件下if self为false。 - John Gordon
什么是self https://www.geeksforgeeks.org/self-in-python-class/ self可以为false吗?https://stackoverflow.com/questions/53103320/when-is-self-statement-true-and-when-is-false - Thavas Antonio
1个回答

3

它检查实例的真值,仅在其为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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接