lib.py
#! /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")
test1.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
test2.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
在lib.py文件中修补套接字gethostbyname后,我从test * .py导入其方法get()并运行。如果已导入套接字库,它将被lib.py导入覆盖,但是,如果先导入lib.py,稍后导入套接字将不会带回原来的套接字系统库,这让我感到困惑。 / p>
为什么表现得像这样?
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.
答案 0 :(得分:1)
py文件您正在使用以下行
socket.gethostbyname=gethostbyname
这就是为什么它总是在你的lib.py文件中使用gethostname
的原因。如果删除它,它将在gethostname
库中使用socket
方法。如果要在lib.py中使用gethostname,请使用lib.gethostname
。
PFB详细解释您的问题 在lib.py中
#! /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
<强>摘要强>
socket.gethostbyname=gethostbyname
),并在任何地方导入lib想要并致电lib.gethostname