在 Python 中的函数名前使用 'if not' 是什么意思?
What does it mean to use 'if not' before a function name in Python?
我遇到了一些我无法解决的代码,并且没有提供解释。我试过了!该代码分为两部分并运行计算机健康检查。在第二个块中,'if not' 行是什么意思? (我不熟悉以这种方式使用函数名)。评论显示了它的作用,但我对它的工作原理很感兴趣。并且在同一行中,括号中的斜线是什么意思?
#!/usr/bin/env python3
import requests
import socket
def check_localhost():
localhost = socket.gethostbyname('localhost')
return localhost == "127.0.0.1"
def check_connectivity():
request = requests.get("http://www.google.com")
return request == 200
#!/usr/bin/env python3
from network import *
import shutil
import psutil
def check_disk_usage(disk):
"""Verifies that there's enough free space on disk"""
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
"""Verifies that there's enough unused CPU"""
usage = psutil.cpu_percent(1)
return usage < 75
# If there's not enough disk, or not enough CPU, print an error
if not check_disk_usage('/') or not check_cpu_usage():
print("ERROR!")
elif check_localhost() and check_connectivity():
print("Everything ok")
else:
print("Network checks failed")
Python中的not
等同于其他语言中的!
;这是一个否定者。它 returns true if the following statement is not true,否则为 false。
据推测,括号中的 /
指的是 Unix 文件系统中的根目录。
所以那一行是说,“如果 root 所在的磁盘 space 不够,或者 cpu 磁盘不够,则打印错误。” check_disk_usage(folder)
和 check_cpu_usage()
这两个函数 return boolean true(表示 OK)或 false(表示不 OK)。
我遇到了一些我无法解决的代码,并且没有提供解释。我试过了!该代码分为两部分并运行计算机健康检查。在第二个块中,'if not' 行是什么意思? (我不熟悉以这种方式使用函数名)。评论显示了它的作用,但我对它的工作原理很感兴趣。并且在同一行中,括号中的斜线是什么意思?
#!/usr/bin/env python3
import requests
import socket
def check_localhost():
localhost = socket.gethostbyname('localhost')
return localhost == "127.0.0.1"
def check_connectivity():
request = requests.get("http://www.google.com")
return request == 200
#!/usr/bin/env python3
from network import *
import shutil
import psutil
def check_disk_usage(disk):
"""Verifies that there's enough free space on disk"""
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
"""Verifies that there's enough unused CPU"""
usage = psutil.cpu_percent(1)
return usage < 75
# If there's not enough disk, or not enough CPU, print an error
if not check_disk_usage('/') or not check_cpu_usage():
print("ERROR!")
elif check_localhost() and check_connectivity():
print("Everything ok")
else:
print("Network checks failed")
not
等同于其他语言中的!
;这是一个否定者。它 returns true if the following statement is not true,否则为 false。
据推测,括号中的 /
指的是 Unix 文件系统中的根目录。
所以那一行是说,“如果 root 所在的磁盘 space 不够,或者 cpu 磁盘不够,则打印错误。” check_disk_usage(folder)
和 check_cpu_usage()
这两个函数 return boolean true(表示 OK)或 false(表示不 OK)。