公开__main__

时间:2010-06-30 20:22:58

标签: python function main iterable

这在python中是合法的吗?似乎工作......

谢谢

# with these lines you not need global variables anymore

if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

var_in_main = 0  # now any var is a global var, you can access any var from everywhere

def fun(*args, **kwargs):

    self = fun
    self.var_in_fun = 'I am a var into fun'

    if args:
        returnList = []
        for request in args:
            returnList.append( getattr(self, request , 'Sorry, no var named "%s" into fun.' % request ) )

        if len(returnList) == 1:
            return returnList[0]
        else:
            return returnList

    elif kwargs:
        for k,v in kwargs.iteritems():

            reset = kwargs.get('reset', None)
            if reset:
                main.var_in_main = 0

            if k == 'times':
                for i in range(v):
                    fun()

            setattr(self, k, v)

    else: # when no args or kwars, execute.
        main.var_in_main += 1
        print ' -', main.var_in_main
        return self


# testing 

print '\nSETTING AND GETTING VARS'

print '     ', fun('var_in_fun')
print '     ', fun('var_in_fun','erroneus_var_name')
print '     ', fun('var_in_fun','erroneus_var_name')[0]

fun( new_var_in_fun = fun )

print '     ', fun( 'new_var_in_fun' ) 
print '     ', fun

print '\nMULTIFUNCTION'

fun()()()()    
fun()
fun()()()

print '\nRESET AND THEN LOOP'

fun( reset = 1)
fun( times = 3 )

print '\nRESET AND LOOP, IN ONE SHOT'

fun( reset= 1, times = 100  )

输出

SETTING AND GETTING VARS
      I am a var into fun
      ['I am a var into fun', 'Sorry, no var named "erroneus_var_name" into fun.']
      I am a var into fun
      <function fun at 0x44f930>
      <function fun at 0x44f930>

MULTIFUNCTION
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8

RESET AND THEN LOOP
 - 1
 - 2
 - 3

RESET AND LOOP, IN ONE SHOT
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7

  --- goes on and on -----

 - 95
 - 96
 - 97
 - 98
 - 99
 - 100

1 个答案:

答案 0 :(得分:3)

if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

这是一种非常脆弱的方法,因为它依赖于包内所有模块的相对导入行为。有一个更好的解决方案 - 更快,更简洁,更可靠:

import sys
main = sys.modules[__name__]

名称main的奇怪选择仍然存在(当我使用这种方法时,我通常会使用类似thismodule的东西),但现在可以采用绑定该名称的方法。