“如果自我:”是什么意思?

2024-05-13 22:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

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

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

bird = Bird()
bird.reproduce_sound()

{}是什么意思?什么情况下reproduce_sound函数调用不打印任何内容


Tags: self内容ifinitdef情况classprint
1条回答
网友
1楼 · 发布于 2024-05-13 22:25:11

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

相关问题 更多 >