例子:
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
函数调用不会打印任何内容?
例子:
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
__bool__
方法,以便在所需条件下if self
为false。 - John Gordon