首页 > 解决方案 > 其中哪一个是正确的语法?

问题描述

初级程序员在这里。我正在制作一个简单的程序来显示我的计算机本地 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)))

提前致谢。

标签: pythonsyntax

解决方案


我会说第一个。它的优点是总是返回 a string,如果没有,它会抛出异常。这是一种可预测和可理解的行为。这意味着它更容易记录,并且无法访问您的源代码的人可以理解和使用该FetchExternalAddress()方法。

只要您正确记录您的方法,表明它返回 a并在未检测到有效的 Internet 连接时string抛出。Exception

您还应该避免像您的方法那样的副作用print("No internet connection"),因为它可能会导致用户意外打印。


推荐阅读