码迷,mamicode.com
首页 > 编程语言 > 详细

关于PYTHON的反射,装饰的练习

时间:2016-01-04 11:40:41      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

 

从基本概念,简单例子才能慢慢走到高级一点的地方。

另外,PYTHON的函数式编程也是我很感兴趣的一点。

总体而言,我觉得OOP可以作大的框架和思路,FP能作细节实现时的优雅牛X。

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
“自省”应该是原本的概念,特指在运行时获得object自身信息,这一能力
“反射”是自省的一种实现方式,是具体的。
自省是“道”,反射是“术”。

好比“变量作用域”是一种概念,而“闭包”是作用域中的一种特定技术。

一种语言可以有完整的自省能力而没有“反射”,也可以有完整的作用域功能而没有“闭包”

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import time

def timeit(func):

    def wrapper():

        start = time.clock()
        func()
        end = time.clock()
        print used: , end - start
    return wrapper

@timeit
# foo = timeit(foo)
def foo():
    print in foo()
    
print foo()
#coding: UTF-8
import sys #  模块,sys指向这个模块对象
import inspect
def foo(): pass # 函数,foo指向这个函数对象
 
class Cat(object): # 类,Cat指向这个类对象
    def __init__(self, name=kitty):
        self.name = name
    def sayHi(self): #  实例方法,sayHi指向这个方法对象,使用类或实例.sayHi访问
        print self.name, says Hi! # 访问名为name的字段,使用实例.name访问
 
cat = Cat() # cat是Cat类的实例对象
 
print Cat.sayHi # 使用类名访问实例方法时,方法是未绑定的(unbound)
print cat.sayHi # 使用实例访问实例方法时,方法是绑定的(bound)

cat = Cat(kitty)
 
print cat.name # 访问实例属性
cat.sayHi() # 调用实例方法
 
print dir(cat) # 获取实例的属性名,以列表形式返回
if hasattr(cat, name): # 检查实例是否有这个属性
    setattr(cat, name, tiger) # same as: a.name = ‘tiger‘
print getattr(cat, name) # same as: print a.name
 
getattr(cat, sayHi)() # same as: cat.sayHi()

print Cat.__doc__           # None
print Cat.__name__          # Cat
print Cat.__module__        # __main__
print Cat.__bases__         # (<type>,)
print Cat.__dict__          # {‘__module__‘: ‘__main__‘, ...}</type>

print cat.__dict__
print cat.__class__
print cat.__class__ == Cat # True

im = cat.sayHi
print im.im_func
print im.im_self # cat
print im.im_class # Cat

co = cat.sayHi.func_code
print co.co_argcount        # 1
print co.co_names           # (‘name‘,)
print co.co_varnames        # (‘self‘,)
print co.co_flags & 0b100   # 0


im = cat.sayHi
if inspect.isroutine(im):
    im()

print inspect.getmro(Cat)
#(<class ‘__main__.Cat‘>, <type ‘object‘>)
print Cat.__mro__
#(<class ‘__main__.Cat‘>, <type ‘object‘>)
class Dog: pass
print inspect.getmro(Dog)
#(<class __main__.Dog at 0x...>,)
print Dog.__mro__ # AttributeError

技术分享

技术分享

 

关于PYTHON的反射,装饰的练习

标签:

原文地址:http://www.cnblogs.com/aguncn/p/5098228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!