from functools import partial, wraps
class Staticmethod(object):
def __init__(self, function):
wraps(function)(self)
def __get__(self, instance, owner):
return partial(self.__wrapped__)
class ClassMethod(object):
def __init__(self, func):
wraps(func)(self)
def __get__(self, instance, owner):
return partial(self.__wrapped__, owner)
class Property(object):
def __init__(self, fget=None, fset=None, fdel=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self, instance, owner):
if instance is None:
return self
if not callable(self.fget):
raise AttributeError('not callable')
return self.fget(instance)
def __set__(self, instance, value):
if instance is None:
return self
if not callable(self.fset):
raise AttributeError('not callable')
print('call me')
return self.fset(instance, value)
def setter(self, fset):
self.fset = fset
return self
def deleter(self, fdel):
self.fdel = fdel
class Hello(object):
def __init__(self, x):
self.x = x
@Staticmethod
def hello(*args, **kwargs):
print('static method')
def bar(*args, **kwargs):
print(args)
@staticmethod
def abc(*args, **kwargs):
print(args)
print(kwargs)
print('abc')
@classmethod
def foo(cls):
print(cls)
print('class method')
@ClassMethod
def zzz(klass, *args, **kwargs):
print(klass)
print(args)
print(kwargs)
@Property
def yyy(self):
print('yyy', self.x)
@yyy.setter
def yyy(self, value):
self.x = value
print(self.x)
# abc = yyy.setter(abc)
# yyy = Property(fget=yyy,fset=None,fdel=None)
h = Hello(123)
h.hello()
h.abc(1,2, a='a', b='b')
h.foo()
h.bar(1,2,3)
h.zzz(12,3, test='test')
h.yyy
h.yyy = 10
h.yyy
============output==========
static method
(1, 2)
{'a': 'a', 'b': 'b'}
abc
<class '__main__.Hello'>
class method
(<__main__.Hello object at 0x054E6F70>, 1, 2, 3)
<class '__main__.Hello'>
(12, 3)
{'test': 'test'}
yyy 123
call me
call------------
10
yyy 10
实现Python静态装饰器、类装饰器、Property装饰器
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 属性property 私有属性添加getter和setter方法 对于类对象的私有属性,我们不能直接调用,可以添加...
- 虽然人们能利用函数闭包(function clouser)写出简单的装饰器,但其可用范围常受限制。多数实现装饰器的...
- 有时候我们很希望看到程序中某个函数或某个代码段的耗时情况,那么该如何办呢?本文用两种方式实现了代码计时器的功能,第...
- 阅读完马上行动: 1.交流清单,每个月认识新的朋友,每个月需要见面,电话,微信维护的老朋友,朋友生日。 2.准备两...