2011-10-13 32 views
1

舉個例子,說我有一個變量定義,其中可能有多個在python中,有沒有辦法找到包含變量或其他對象從對象本身的模塊?

from __ import * 
from ____ import * 

有沒有辦法找出其中的命名空間的變量之一定義?

編輯

謝謝,但我已經明白,進口*通常被認爲是拙劣的形式。這不是問題,但無論如何我沒有寫出來。有一種方法可以找到變量的來源。

+4

這正是您不應該使用通配符導入的原因。 – Falmarri

回答

5

這就是爲什麼它被認爲是不好的形式在大多數情況下在Python中使用from __ import *。請使用from __ import myFuncimport __ as myLib。然後當你需要myLib的東西時,它不會在其他事物上重疊。

如需查找當前命名空間中的內容,請查看pprint library,the dir builtin,the locals builtin,and the globals builtin

3

號,由from blah import *定義的名稱不會保留有關他們來自何處的任何信息。這些值可能有線索,例如,類具有__module__屬性,但它們可能已在一個模塊中定義,然後從另一個模塊導入,因此您不能指望它們是您所期望的值。

0

如果你在解釋器中調用方法本身,它會告訴你它的父模塊是什麼。

例如:

>>> from collections import * 
>>> deque 
<type 'collections.deque'> 
1

排序-,例如:

>>> from zope.interface.common.idatetime import * 
>>> print IDate.__module__ 
'zope.interface.common.idatetime' 
>>> print Attribute.__module__ 
'zope.interface.interface' 

Attribute的模塊似乎因爲那令人驚訝的是不是你進口,但它Attribute類型被定義爲。縱觀zope/interface/common/idatetype.py,我們看到:

from zope.interface import Interface, Attribute 

這解釋了__module__值。您還會遇到從其他模塊導入的類型實例的問題。假設您創建了一個名爲att一個Attribute實例:

>>> att = Attribute('foo') 
>>> print att.__module__ 
'zope.interface.interface' 

同樣,你在學習,其中類型來了,但不是變量定義在哪裏。

很可能是最大的原因,不使用通配符進口的,你不知道你會得到什麼,他們污染您的命名空間和可能揍其他類型/變量。

>>> class Attribute(object): 
... foo = 9 
... 
>>> print Attribute.foo 
9 
>>> from zope.interface.common.idatetime import * 
>>> print Attribute.foo 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: type object 'Attribute' has no attribute 'foo' 

即使今天import *作品無碰撞,也不能保證它不會與該包被導入未來的更新發生。

相關問題