pass语句

作为占位符

In [1]:
#python不允许空代码块
if 1 > 0 :
  File "<ipython-input-1-516673b5c7ed>", line 2
    if 1 > 0 :
              ^
IndentationError: expected an indented block
In [2]:
#我们需要利用pass语句来占位
if 1 > 0 :
    pass

del语句

赋值时,内存会开辟空间给这个值
当值改变时,原来的那个值就会在内存中消失(称为垃圾收集)
我们可以使用del语句,让一个对象删除消失
注意:python里是不能删除值的,我们删除的是这个对象,这个名称

使用exec和eval执行和求值字符串

动态创造python代码,然后将其作为表达式和语句执行

  • exec语句,执行一个命令字符串(语句)
In [3]:
exec "x = 1"
In [4]:
x
Out[4]:
1
In [5]:
#但是采用命令字符串可能会扰乱命名空间
In [6]:
from math import sqrt
In [7]:
exec "sqrt = 1"
In [8]:
sqrt(4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-718d7f173e1d> in <module>()
----> 1 sqrt(4)

TypeError: 'int' object is not callable
In [9]:
#黑客有可能透过这样来破坏命名空间,影响某些关键函数的使用
#命名空间是一个放置变量的地方  
#我们可以手动给予一个字典来存储这个变量
In [15]:
from math import sqrt
In [16]:
scope = {}
In [17]:
exec "sqrt = 1" in scope
In [18]:
sqrt(4)    #这回命名空间就不会被干扰啦
Out[18]:
2.0
In [20]:
len(scope)
Out[20]:
2
In [21]:
scope
Out[21]:
{'__builtins__': {'ArithmeticError': ArithmeticError,
  'AssertionError': AssertionError,
  'AttributeError': AttributeError,
  'BaseException': BaseException,
  'BufferError': BufferError,
  'BytesWarning': BytesWarning,
  'DeprecationWarning': DeprecationWarning,
  'EOFError': EOFError,
  'Ellipsis': Ellipsis,
  'EnvironmentError': EnvironmentError,
  'Exception': Exception,
  'False': False,
  'FloatingPointError': FloatingPointError,
  'FutureWarning': FutureWarning,
  'GeneratorExit': GeneratorExit,
  'IOError': IOError,
  'ImportError': ImportError,
  'ImportWarning': ImportWarning,
  'IndentationError': IndentationError,
  'IndexError': IndexError,
  'KeyError': KeyError,
  'KeyboardInterrupt': KeyboardInterrupt,
  'LookupError': LookupError,
  'MemoryError': MemoryError,
  'NameError': NameError,
  'None': None,
  'NotImplemented': NotImplemented,
  'NotImplementedError': NotImplementedError,
  'OSError': OSError,
  'OverflowError': OverflowError,
  'PendingDeprecationWarning': PendingDeprecationWarning,
  'ReferenceError': ReferenceError,
  'RuntimeError': RuntimeError,
  'RuntimeWarning': RuntimeWarning,
  'StandardError': StandardError,
  'StopIteration': StopIteration,
  'SyntaxError': SyntaxError,
  'SyntaxWarning': SyntaxWarning,
  'SystemError': SystemError,
  'SystemExit': SystemExit,
  'TabError': TabError,
  'True': True,
  'TypeError': TypeError,
  'UnboundLocalError': UnboundLocalError,
  'UnicodeDecodeError': UnicodeDecodeError,
  'UnicodeEncodeError': UnicodeEncodeError,
  'UnicodeError': UnicodeError,
  'UnicodeTranslateError': UnicodeTranslateError,
  'UnicodeWarning': UnicodeWarning,
  'UserWarning': UserWarning,
  'ValueError': ValueError,
  'Warning': Warning,
  'ZeroDivisionError': ZeroDivisionError,
  '__IPYTHON__': True,
  '__IPYTHON__active': 'Deprecated, check for __IPYTHON__',
  '__debug__': True,
  '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.",
  '__import__': <function __import__>,
  '__name__': '__builtin__',
  '__package__': None,
  'abs': <function abs>,
  'all': <function all>,
  'any': <function any>,
  'apply': <function apply>,
  'basestring': basestring,
  'bin': <function bin>,
  'bool': bool,
  'buffer': buffer,
  'bytearray': bytearray,
  'bytes': str,
  'callable': <function callable>,
  'chr': <function chr>,
  'classmethod': classmethod,
  'cmp': <function cmp>,
  'coerce': <function coerce>,
  'compile': <function compile>,
  'complex': complex,
  'copyright': Copyright (c) 2001-2014 Python Software Foundation.
  All Rights Reserved.
  
  Copyright (c) 2000 BeOpen.com.
  All Rights Reserved.
  
  Copyright (c) 1995-2001 Corporation for National Research Initiatives.
  All Rights Reserved.
  
  Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
  All Rights Reserved.,
  'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
      for supporting Python development.  See www.python.org for more information.,
  'delattr': <function delattr>,
  'dict': dict,
  'dir': <function dir>,
  'divmod': <function divmod>,
  'dreload': <function IPython.lib.deepreload.reload>,
  'enumerate': enumerate,
  'eval': <function eval>,
  'execfile': <function execfile>,
  'file': file,
  'filter': <function filter>,
  'float': float,
  'format': <function format>,
  'frozenset': frozenset,
  'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <IPython.kernel.zmq.zmqshell.ZMQInteractiveShell object at 0x7f8c03903a50>>,
  'getattr': <function getattr>,
  'globals': <function globals>,
  'hasattr': <function hasattr>,
  'hash': <function hash>,
  'help': Type help() for interactive help, or help(object) for help about object.,
  'hex': <function hex>,
  'id': <function id>,
  'input': <function IPython.kernel.zmq.ipkernel.<lambda>>,
  'int': int,
  'intern': <function intern>,
  'isinstance': <function isinstance>,
  'issubclass': <function issubclass>,
  'iter': <function iter>,
  'len': <function len>,
  'license': Type license() to see the full license text,
  'list': list,
  'locals': <function locals>,
  'long': long,
  'map': <function map>,
  'max': <function max>,
  'memoryview': memoryview,
  'min': <function min>,
  'next': <function next>,
  'object': object,
  'oct': <function oct>,
  'open': <function open>,
  'ord': <function ord>,
  'pow': <function pow>,
  'print': <function print>,
  'property': property,
  'range': <function range>,
  'raw_input': <function IPython.kernel.zmq.ipkernel.<lambda>>,
  'reduce': <function reduce>,
  'reload': <function reload>,
  'repr': <function repr>,
  'reversed': reversed,
  'round': <function round>,
  'set': set,
  'setattr': <function setattr>,
  'slice': slice,
  'sorted': <function sorted>,
  'staticmethod': staticmethod,
  'str': str,
  'sum': <function sum>,
  'super': super,
  'tuple': tuple,
  'type': type,
  'unichr': <function unichr>,
  'unicode': unicode,
  'vars': <function vars>,
  'xrange': xrange,
  'zip': <function zip>},
 'sqrt': 1}
In [22]:
#呼……这个字典内容可真是多,这是因为内建的__builtins__字典自动包含了所有的内建函数和值
  • eval函数,执行一个命令字符串(表达式)
In [1]:
eval( 'raw_input("Enter your name: ")' )
Enter your name: Zk

Out[1]:
'Zk'
In [2]:
#表达式一般不会像语句那样重新为变量赋值
#但是eval确实也可以使用命名空间
#可以提供一个全局的,一个局部的
#全局必须是字典,局部可以是任何形式的映射
  • 嘿嘿,我们也可以提前在创建的命名空间前放入一些变量
In [4]:
scope = {}
In [5]:
exec 'x = 2' in scope
In [6]:
eval('x*x', scope)  #指定命名空间scope,呼呼,里面可是有x =2
Out[6]:
4

其实,这两个函数并不常用,但却是一个有力的工具

In []: