初学者程序员在这里。我正在做一个简单的程序来显示我的计算机本地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)))
提前谢谢
我会说第一个。它的优点是总是返回一个
string
,如果不返回,它就会抛出一个异常。这是一种可以预见和理解的行为。这意味着文档更容易编写,而且无法访问源代码的人可以理解并使用FetchExternalAddress()
方法只要您正确地记录您的方法,表明它返回一个
string
,并在没有检测到有效的Internet连接时抛出Exception
您还应该避免方法中的
print("No internet connection")
之类的副作用,因为它可能会导致用户意外打印相关问题 更多 >
编程相关推荐