导入的python lib占主导地位

时间:2017-10-31 01:38:37

标签: python python-2.7

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. 

1 个答案:

答案 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

<强>摘要

  1. 首先,改变内置python库并不是一个好主意
  2. 如果您不想使用自定义的gethostname函数,请在py(比如lib.py)文件中定义相同的内容(不覆盖原始文件,即不像socket.gethostbyname=gethostbyname),并在任何地方导入lib想要并致电lib.gethostname
相关问题