"if self:" 是什么意思?

What does "if self:" mean?

示例:

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