Python,循环导入后检查对象的类型
这是两个文件,foo.py 和 bar.py bar.py 有...
from foo import *
...在顶部。 bar.py 使用 foo 定义的类型。
从 foo 导入 bar.py 时,我无法确定对象的类型。 看下面的示例,为什么调用 isinstance 返回 False? 如何检查这些类型是否相同?
谢谢,
===== foo.py =====
#!/usr/bin/env python
class Spam(object):
def __init__(self, x):
self.x = x
def funcA(self):
print 'function a'
def __str__(self):
return 'Spam object %s' % repr(self.x)
class Eggs(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def funcB(self):
print 'function b'
def __str__(self):
return "Eggs object (%s, %s, %s)" % (repr(self.x), repr(self.y), repr(self.z))
def main(fname):
if not fname.endswith('.py'):
raise Exception("Must be a .py file")
module = __import__(fname[:-3])
for item in module.DATA:
if isinstance(item, Spam):
item.funcA()
elif isinstance(item, Eggs):
item.funcB()
print item
if __name__ == '__main__':
import sys
for fname in sys.argv[1:]:
main(fname)
sys.exit(0)
===== bar.py =====
from foo import *
DATA=[
Spam("hi"),
Spam("there"),
Eggs(1, 2, 3),
]
Here are two files, foo.py and bar.py
bar.py has...
from foo import *
...at the top. bar.py uses types defined n foo.
When importing bar.py from foo I am having trouble determining the types of objects.
Looking at the example below why do the calls to isinstance return False?
How can I check if these types are the same?
Thanks,
===== foo.py =====
#!/usr/bin/env python
class Spam(object):
def __init__(self, x):
self.x = x
def funcA(self):
print 'function a'
def __str__(self):
return 'Spam object %s' % repr(self.x)
class Eggs(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def funcB(self):
print 'function b'
def __str__(self):
return "Eggs object (%s, %s, %s)" % (repr(self.x), repr(self.y), repr(self.z))
def main(fname):
if not fname.endswith('.py'):
raise Exception("Must be a .py file")
module = __import__(fname[:-3])
for item in module.DATA:
if isinstance(item, Spam):
item.funcA()
elif isinstance(item, Eggs):
item.funcB()
print item
if __name__ == '__main__':
import sys
for fname in sys.argv[1:]:
main(fname)
sys.exit(0)
===== bar.py =====
from foo import *
DATA=[
Spam("hi"),
Spam("there"),
Eggs(1, 2, 3),
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过打印
Spam
、Eggs
以及item
类型?foo.py
模块运行两次,一次作为主程序,一次由bar.py
导入时运行。在主程序中,
Spam
和Eggs
分别定义为__main__.Spam
和__main__.Eggs
。在导入的模块中,
Spam
和Eggs
定义为foo.Spam
和foo.Eggs
。__main__.Spam
!=foo.Spam
,__main__.Eggs
!=foo.Eggs
。Have you tried printing
Spam
,Eggs
and the type ofitem
?The
foo.py
module is run twice, once as the main program and once when it's imported bybar.py
.In the main program,
Spam
andEggs
are defined as__main__.Spam
and__main__.Eggs
.In an imported module,
Spam
andEggs
are defined asfoo.Spam
andfoo.Eggs
.__main__.Spam
!=foo.Spam
,__main__.Eggs
!=foo.Eggs
.与:
我得到:
将 main 代码和 main 函数移动到另一个文件并导入 foo 并将工作
With:
I got :
Move the main code and the main function to adifferent file and import foo and will work