关于python中的导入模块和方法名称 [英] On import modules and method names in python

查看:76
本文介绍了关于python中的导入模块和方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我导入以下两个模块,如下所示:

Suppose I import the following two modules as follows:

from sympy import *
from numpy import *

两个模块均定义了exp()函数. python如何选择使用哪个?如上所述导入模块后,是否可以区分这些功能?在这种情况下,存在什么机制可以警告用户?考虑IDLE

both modules have an exp() function defined. How does python pick which one to use? Is there a way to distinguish these functions after the modules have been imported as above? What mechanism exists to warn the user when this is the case? Consider the following set of commands in IDLE

=============================== RESTART: Shell ===============================
>>> from sympy import *
>>> from numpy import *
>>> exp(5)
148.4131591025766
>>> c = symbols('c')
>>> exp(c)
Traceback (most recent call last):
  File "<pyshell#162>", line 1, in <module>
    exp(c)
AttributeError: 'Symbol' object has no attribute 'exp'
>>> 
=============================== RESTART: Shell ===============================
>>> from sympy import *
>>> c = symbols('c')
>>> exp(c)
exp(c)

似乎默认情况下 python在numpy中使用exp()定义,但是在sympy识别的对象类型上调用它时,会引发错误,从而呈现sympy.exp()功能无法使用.

It appears that by default python uses the exp() definition in numpy however when it is called on an object type recognized by sympy it throws an error which renders the sympy.exp() function unuseable.

对于这种情况,我知道两个包中都存在函数,但是如果不存在该怎么办?应该有某种机制可以警告用户避免真正令人困惑的情况…….python社区如何处理这个问题?

For this case, I know that the functions exist in both packages but what if I don't? There ought to be some mechanism that warns the user to avoid really confusing situations.... How does the python community deal with this issue?

推荐答案

它不是选择".当您执行from sympy import *时,它将所有名称从sympy导入到当前名称空间中.而当您执行from numpy import *时,它也会执行相同的操作.先前定义的所有内容都将被覆盖.这与您做的完全相同:

It doesn't "pick". When you do from sympy import * it imports all names from sympy into the current namespace; and when you do from numpy import * it does the same thing. Anything that is previously defined is overwritten. This is exactly the same as if you did:

foo = 'bar'
foo = 'baz'

很明显,foo现在具有值"baz",即使您最初将其定义为"bar".

Clearly, foo now has the value "baz" even though you initially defined it as "bar".

解决方案是不这样做;您应该明确导入所需的内容:

The solution is not to do this; you should import the things you need explicitly:

from sympy import exp, ....
from numpy import ....

这篇关于关于python中的导入模块和方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆