python classmethod,staticmethod实现

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 = function

class 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 = function


class Class2(object):
    @my_staticmethod
    def get_user(x):
        return x, "get_user"

print Class2.get_user("###")
#==========
('###', 'get_user')

你可能感兴趣的:(python)