Python3.X新特性之print和exec

  print

  print 现在是一个函数,不再是一个语句。<语法更为清晰>

  实例1

  打开文件 log.txt 以便进行写入并将对象指定给 fid。然后利用 print将一个字符串重定向给文件 fid。

  fid=open("log.txt",'w')

  print("log.txt", file=fid)

  print("hello")

  #fid = open("log.txt", 'w')

  #print>>fid, "log text"

  #print "hello"

  #print("Foo", "Bar", sep="%")

  Python3.X执行结果:

Python3.X新特性之print和exec

#fid=open("log.txt",'w')

  #print("log.txt", file=fid)

  #print("hello")

  fid = open("log.txt", 'w')

  print>>fid, "log text"

  print "hello"

  #print("Foo", "Bar", sep="%")

  Python2.X执行结果:

Python3.X新特性之print和exec

  实例2

print("Foo", "Bar", sep="%")

Python3.X新特性之print和exec

  #fid=open("log.txt",'w')

  #print("log.txt", file=fid)

  #print("hello")

  #fid = open("log.txt", 'w')

  #print>>fid, "log text"

  #print "hello"

  print("Foo", "Bar", sep="%")

  Python3.X中执行结果:

Python3.X新特性之print和exec

  exec

  exec()作为函数,只操作globals()和locals()函数返回的字典。locals()函数返回的字典实际上是局部变量的一个副本。exec()函数中进行的赋值只修改了局部变量的这份副本,而非局部变量本身。

  Python3.X新特性之print和exec

  实例:

  def foo():

  exec('a=4')

  print(a)

  foo()

  #def foo():

  # _locals = locals()

  # exec('a=4',globals(),_locals)

  # a = _locals['a']

  #print (a)

  #foo()

  Python2.X中执行结果:

Python3.X新特性之print和exec

Python3.X中执行结果:

Python3.X新特性之print和exec

#def foo():

  # exec('a=4')

  # print(a)

  #foo()

  def foo():

  _locals = locals()

  exec('a=4',globals(),_locals)

  a = _locals['a']

  print (a)

  foo()

  Python3.X中执行结果:

Python3.X新特性之print和exec

原文链接:http://www.maiziedu.com/wiki/python/exec/

上一篇:cron任务解释


下一篇:【转载】Python 代码调试技巧