以下哪一个是正确的语法?

2024-10-01 07:36:08 发布

您现在位置: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)))

提前谢谢


Tags: fromimportipgetreturnaddressdefrequests
1条回答
网友
1楼 · 发布于 2024-10-01 07:36:08

我会说第一个。它的优点是总是返回一个string,如果不返回,它就会抛出一个异常。这是一种可以预见和理解的行为。这意味着文档更容易编写,而且无法访问源代码的人可以理解并使用FetchExternalAddress()方法

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

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

相关问题 更多 >