python - 其中哪一个是正确的语法?
问题描述
初级程序员在这里。我正在制作一个简单的程序来显示我的计算机本地 IP 地址和网络的外部 IP 地址。这真的不是问题,而更多的是一个问题。
那么,这些格式中的哪一种是首选语法?
1.
# -*- coding: utf-8 -*-
from socket import gethostname, gethostbyname
from requests import get
from requests.exceptions import ConnectionError
def FetchLocalAddress():
hostname = gethostname()
ip = gethostbyname(hostname)
return ip
def FetchExternalAddress():
ip = get('https://api.ipify.org').text
return ip
try:
print('Local ip-address: {}'.format(str(FetchLocalAddress())))
print('External ip-address: {}'.format(str(FetchExternalAddress())))
except ConnectionError:
print('No internet connection.')
2.
# -*- coding: utf-8 -*-
from socket import gethostname, gethostbyname
from requests import get
from requests.exceptions import ConnectionError
def FetchLocalAddress():
hostname = gethostname()
ip = gethostbyname(hostname)
return ip
def FetchExternalAddress():
try:
ip = get('https://api.ipify.org').text
return ip
except ConnectionError:
print('No internet connection.')
print('Local ip-address: {}'.format(str(FetchLocalAddress())))
external = FetchExternalAddress()
if external is not None:
print('External ip-address: {}'.format(str(external)))
提前致谢。
解决方案
我会说第一个。它的优点是总是返回 a string
,如果没有,它会抛出异常。这是一种可预测和可理解的行为。这意味着它更容易记录,并且无法访问您的源代码的人可以理解和使用该FetchExternalAddress()
方法。
只要您正确记录您的方法,表明它返回 a并在未检测到有效的 Internet 连接时string
抛出。Exception
您还应该避免像您的方法那样的副作用print("No internet connection")
,因为它可能会导致用户意外打印。
推荐阅读
- amazon-web-services - terraform 多个提供商无法使用 s3 存储桶
- php - 如何为数据库数组结果设置不同的超链接?
- python - 加载预训练网络时,错误表明尺寸变平
- c# - 了解 Mvc 核心标识
- swift - Xcode 未检测 gomobile(绑定)生成的框架上的架构
- javascript - 当用户在按钮单击时输入无效的日期格式时如何显示验证错误?
- python - 找出可用作缺失值建议的特定字符串
- mysql - 你如何多次打开/关闭mysql连接?
- rust - 带有类型问题的 Future 和 Stream 嵌套
- r - 将插入符号的混淆矩阵应用于由 data.frames 组成的列表,从而产生多个混淆矩阵