python classmethod,staticmethod实现

来源:互联网 发布:深入理解php内核 pdf 编辑:程序博客网 时间:2024/06/05 15:10

classmethod

class my_classmethod(object):    def __get__(self, obj, type=None):        def wrapper(*args, **kwargs):            return self.function(type, *args, **kwargs)        return wrapper    #更简单的写法    def __get__(self, obj, type=None):        return partial(self.function, type) #partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数    def __init__(self, function):        self.function = functionclass Class2(object):    @my_classmethod    def get_user(cls, x):        return x, "get_user"print Class2.get_user("###")#==========('###', 'get_user')

staticmethod

class my_staticmethod(object):    def __get__(self, obj, type=None):        def wrapper(*args, **kwargs):            return self.function(*args, **kwargs)        return wrapper    def __init__(self, function):        self.function = functionclass Class2(object):    @my_staticmethod    def get_user(x):        return x, "get_user"print Class2.get_user("###")#==========('###', 'get_user')
0 0
原创粉丝点击