Python,循环导入后检查对象的类型

发布于 2024-11-25 22:13:53 字数 1288 浏览 1 评论 0原文

这是两个文件,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最终幸福 2024-12-02 22:13:53

您是否尝试过打印SpamEggs以及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)

foo.py 模块运行两次,一次作为主程序,一次由 bar.py 导入时运行。

在主程序中,SpamEggs分别定义为__main__.Spam__main__.Eggs

在导入的模块中,SpamEggs 定义为 foo.Spamfoo.Eggs

__main__.Spam != foo.Spam, __main__.Eggs != foo.Eggs

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.

¢蛋碎的人ぎ生 2024-12-02 22:13:53

与:

if __name__ == '__main__':
    import sys
    main('bar.py')
    sys.exit(0)

我得到:

Spam object 'hi'
Spam object 'there'
Eggs object (1, 2, 3)

ma​​in 代码和 main 函数移动到另一个文件并导入 foo 并将工作

#-- 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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文