如何使用__name__属性获取相应的输出?

时间:2016-10-01 14:28:17

标签: python python-3.x

__name__是python中的特殊属性,具有模块名称的值。

try2.py,try1.py,try3.py的__name__值分别为'try2','try1'和'try3'。

如果try2.py中的条件分别在文件try1.py和try3.py中获得相应的输出,我应该替换什么?

file:try2.py

class A(object):
    a=[]    
def add(self,p,q):
    return p+q
def minus(self,p,q):
    return p-q

#I know that if i replace 'try1' by 'try2' in if condition,
#then this can be executed where try2.py will be imported
if(__name__=='try1'):
    print('runs only if module name is try1')
elif(__name__=='try3'):
    print('runs only if module name is try3')   

file:try1.py

import try2

print(try2.A().add(2,3))

file:try3.py

import try2
print(try2.A().minus(2,3))

1 个答案:

答案 0 :(得分:3)

__name__可能只有两件事。

如果直接运行模块,其__name__将为"__main__"

否则,您必须已导入它;其__name__将是模块的名称。 try2的名称不可能是“try1”或“try3”。