四时宝库

程序员的知识宝库

木兰语言多次引用模块的行为小结(木兰塑造了一个怎样的形象)

续上文《木兰语言的引用相关功能与问题新发现》,对重复引用的各种方式作了更多测试,基于当前理解作一小结。

简言之,由于每次引用模块都对其执行(exec)一次,在多处引用同一模块的情况下,引用顺序和模块位置不同会导致不同结果。暂没想到此种行为的应用场景。

比如在 TypeDef 模块中定义一个类:

type Type1 { ; } 

在同层目录下 Instance1 模块中声明一个个体:

using * in TypeDef

instance1 = Type1() 

那么在另一模块中,先后引用 TypeDef 和 Instance1,如下的 isa 判断(对应 python 的 isinstance)返回 true,意料之中:

using * in TypeDef
using * in Instance1

print(isa(instance1, Type1))

但是以下的三种情况,全都返回 false:

  • 情况 1:
using * in Instance1
using * in TypeDef

print(isa(instance1, Type1)) 
  • 情况 2:
using TypeDef
using Instance1

print(isa(Instance1.instance1, TypeDef.Type1)) 
  • 情况 3:
using Instance1
using TypeDef

print(isa(Instance1.instance1, TypeDef.Type1)) 

而如果 TypeDef 和 Instance1 在包内,行为又略有不同。如下返回 true(注意 TypeDef 在 Instance1 后引用)

using * in test.Instance1
using * in test.TypeDef

print(isa(instance1, Type1)) 

以下的三种情况,全都返回 false:

  • 情况 4:
using * in test.TypeDef
using * in test.Instance1

print(isa(instance1, Type1)) 
  • 情况 5:
using * in test.TypeDef
using test.Instance1

print(isa(test.Instance1.instance1, Type1)) 
  • 情况 6:
using * in test.Instance1
using test.TypeDef

print(isa(instance1, test.TypeDef.Type1)) 

测试用例 集结在此。

为规避,在应用中尽量保持“树式引用”,即一个模块只直接引用一次。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接