python namespace package_python名称空间:__main __。Class不是package.Class的实例

Consider you have two python files as defined below. Say one is a general package (class2), and the other one does specific overrides and serves as the executable (class1).

class1.py:

#!/usr/bin/python

class Test(object):

pass

class Verificator():

def check(self, myObject):

if not isinstance( myObject, Test ):

print "%s is no instance of %s" % (type(myObject),Test)

else:

print "OK!"

if __name__ == '__main__':

from class2 import getTest

v = Verificator()

t = Test()

v.check(t)

s = getTest()

v.check(s)

class2.py:

from class1 import Test

def getTest():

return Test()

What happens is that the first check is OK, where the second fails. The reason is that t is __main__.Test whereas s is class1.Test and v.check() checks for __main__.Test, but at the end of the day it is the same class, right?

Is there a way to write v.check() such that it also accepts class1.Test objects, or any other way to solve this?

解决方案

If you plan to import class1.py from elsewhere, move the top-level code (if __name__ == '__main__': ... to a separate file altogether. That way both the main file and class2 work with the same class1.Test class.

Doing almost anything else opens a can of worms. While you can work around the immediate problem by switching isinstance to type(myObject).__name__ == ..., the fact remains that your Python process contains two Test classes where there should be only one. The otherwise indistinguishable classes know nothing of each other and fail each other's issubclass tests. This practically guarantees hard-to-diagnose bugs further down the line.

EDIT

Another option is to explicitly import the classes from class1 when executing as main, as in your answer. It would be advisable to go one step further and make sure that the classes aren't defined in double. For example, you can move the if __name__ == '__main__' block to the beginning of the file, and end it with sys.exit(0):

if __name__ == '__main__':

import class1, class2

... use only the public API with module prefixes ...

sys.exit(0)

# the rest of the module follows here

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值