标签:
>>> answer = ‘tell me‘ >>> def foo(): ... answer = ‘42‘ ... print answer ... >>> foo() 42 >>> print answer tell me >>>
>>>f = lambda x:x+y >>>f(1) >>>2
>>> def f1(): ... answer = ‘tell me‘ ... def f2(): ... print answer ... f2() ... >>> f1() tell me >>>
>>> answer = ‘tell me‘ >>> def foo(): ... global answer ... answer = ‘42‘ ... print answer ... >>> print answer tell me >>> foo() 42 >>> print answer 42
#定义一个函数 >>> def foo(): ... print ‘bar‘ ... #foo2引用foo >>> foo2 = foo #查看引用计数 >>> import sys #传参也有1次引用所以是3 >>> sys.getrefcount(foo) 3 #输出bar >>> foo2() bar
#test_example.py TEST_NUM = 2 TEST_STR = " test_str " if __name__ == ‘__main__‘: print __name__ print TEST_STR
>>> import test_example as t >>> t.TEST_NUM 2 >>> t.__name__ ‘test_example‘ >>> type(t) <type ‘module‘> >>> dir(t) [‘TEST_NUM‘, ‘TEST_STR‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘]
def my_dec(func): def wrapper(): print ‘before decorator‘ func() print ‘after decorator‘ return wrapper def hello(): print ‘hello‘
@my_dec def hello(): print ‘hello‘
def hello(): print ‘hello‘ hello = my_dec(hello)
def my_dec(func): def wrapper(*arg, **kwargs): print arg, kwargs print ‘before decorator‘ func(*arg,**kwargs) print ‘after decorator‘ return wrapper @my_dec def hello(*arg, **kwargs): print ‘in hello‘ print arg, kwargs print ‘in hello‘ if __name__ == ‘__main__‘: hello(‘the answer is ‘, 42)
@wraps(func)
def coroutine(): while True: y = yield print y c=coroutine() c.send(None) c.send(1) c.send(2) c.send(None)
li=["a","s","d","f"] for idx, ele in enumerate(li): print idx, ele
class Foo: def __init__(self): self.a = 1 f=Foo() f.__class__.__name__ type(f)
>>> di={} >>> dir(di) #居家旅行必备的dir >>> class Foo: ... """ ... hello from Foo ... """ ... def __init__(self): ... self.a = 1 ... self.b = ‘2‘ ... def reset(self): ... self.c = 0 ... >>> f=Foo() >>> Foo.__dict__ {‘reset‘: <function reset at 0x8e8d1b4>, ‘__module__‘: ‘__main__‘, ‘__doc__‘: ‘\n hello from Foo\n ‘, ‘__init__‘: <function __init__ at 0x8e8d294>} >>> f.__dict__ #拿到object的属性 {‘a‘: 1, ‘b‘: ‘2‘} >>> f.reset() >>> f.__dict__ #属性还能动态增加!似乎很神奇。 {‘a‘: 1, ‘c‘: 0, ‘b‘: ‘2‘} >>>
标签:
原文地址:http://www.cnblogs.com/ifkite/p/4556676.html