导入的python库占主导地位

2024-05-19 10:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗自由基你知道吗

#! /usr/bin/python

def gethostbyname(hostname):
    print "This is different gethostby name"
    return "Hello"

import socket
# Patch the socket library
socket.gethostbyname=gethostbyname

def get():
    print socket.gethostbyname("www.google.com")

测试1.py

#! /usr/bin/python
import socket
print socket.gethostbyname("www.google.com") # <- this works fine
from lib import get
print get()
print socket.gethostbyname("www.google.com") # <- method is changed

108.177.98.105 # proper output from socket library
This is different gethostby name
Hello
None
This is different gethostby name # <- after import, the gethostbyname method is changed 
Hello

测试2.py

#! /usr/bin/python
from lib import get
print get()
import socket
print socket.gethostbyname("www.google.com") <- even import again, the socket gethostbyname is changed

This is different gethostby name
Hello
None
This is different gethostby name
Hello

在中修补套接字gethostbyname之后自由基文件中,我从test*.py导入其方法get(),然后运行。如果已导入套接字库,则自由基但是,如果导入自由基首先,以后导入socket不会带回原来的socket系统库,这让我很困惑。你知道吗

为什么会这样?你知道吗

Python 2.7.10 (default, Feb  7 2017, 00:08:15) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information. 

Tags: nameimportcomhellogetiswwwgoogle
1条回答
网友
1楼 · 发布于 2024-05-19 10:22:41

py文件您正在使用下面的行 socket.gethostbyname=gethostbyname 这就是为什么它总是在你的语言中使用gethostname自由基文件。如果删除,它将使用socket库中的gethostname方法。如果要在中使用gethostname自由基使用lib.gethostname。你知道吗

请详细解释您的问题 英寸自由基

#! /usr/bin/python

def gethostbyname(hostname):
    print "This is different gethostby name"
    return "Hello"

import socket
# Patch the socket library
socket.gethostbyname=gethostbyname
#in the above program since you have given socket.gethostbyname=gethostbyname after that line when you call socket.gethostbyname it assumes that you are calling local gethostbyname

def get():
    print socket.gethostbyname("www.google.com")

test1.py中

#! /usr/bin/python
import socket
print socket.gethostbyname("www.google.com") 

# since you did not import lib before the above line this will work as it is defined in socket library

from lib import get
print get()
print socket.gethostbyname("www.google.com") # <- method is changed
# since you imported lib before the above line and in lib since you have `socket.gethostbyname=gethostbyname` in your lib.py file this will work as it is defined in lib.py

test2.py中

#! /usr/bin/python
from lib import get
print get()
import socket
print socket.gethostbyname("www.google.com") 


# since you imported lib before the above line and in lib since you have `socket.gethostbyname=gethostbyname` in your lib.py file this will work as it is defined in lib.py

摘要

  1. 首先,更改内置python库不是一个好主意
  2. 如果不想自定义gethostname函数,可以在py中定义相同的函数(比如自由基)文件(不重写原始文件,即不像socket.gethostbyname=gethostbyname),并在需要时导入lib并调用lib.gethostname

相关问题 更多 >

    热门问题