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)
sy开发者_开发知识库s.exit(0)
===== bar.py =====
from foo import *
DATA=[
Spam("hi"),
Spam("there"),
Eggs(1, 2, 3),
]
Have you tried printing Spam, Eggs and the type of item?
Spam is <class '__main__.Spam'>
Eggs is <class '__main__.Eggs'>
type of item is <class 'foo.Spam'>
Spam object 'hi'
type of item is <class 'foo.Spam'>
Spam object 'there'
type of item is <class 'foo.Eggs'>
Eggs object (1, 2, 3)
The foo.py module is run twice, once as the main program and once when it's imported by bar.py.
In the main program, Spam and Eggs are defined as __main__.Spam and __main__.Eggs.
In an imported module, Spam and Eggs are defined as foo.Spam and foo.Eggs.
__main__.Spam != foo.Spam, __main__.Eggs != foo.Eggs.
With:
if __name__ == '__main__':
import sys
main('bar.py')
sys.exit(0)
I got :
Spam object 'hi'
Spam object 'there'
Eggs object (1, 2, 3)
Move the main code and the main function to adifferent file and import foo and will work
#-- main.py --
import foo
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, foo.Spam):
item.funcA()
elif isinstance(item, foo.Eggs):
item.funcB()
print item
if __name__ == '__main__':
import sys
main('bar.py')
sys.exit(0)
加载中,请稍侯......
精彩评论