[英]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:
是什么意思? 什么情況下,recreate_sound 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.