如何在Python中创建两个装饰器来执行以下操作?
@makebold
@makeitalic
def say():
return "Hello"
Run Code Online (Sandbox Code Playgroud)
...应该返回:
"<b><i>Hello</i></b>"
Run Code Online (Sandbox Code Playgroud)
我不是试图HTML在一个真实的应用程序中这样做 - 只是试图了解装饰器和装饰器链是如何工作的.
我想了解内置函数的property工作原理.令我困惑的是,property它也可以用作装饰器,但它只在用作内置函数时才需要参数,而不是用作装饰器时.
这个例子来自文档:
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Run Code Online (Sandbox Code Playgroud)
property的论点是getx,setx,delx和文档字符串.
在下面的代码中property用作装饰器.它的对象是x函数,但在上面的代码中,参数中没有对象函数的位置.
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Run Code Online (Sandbox Code Playgroud)
而且,如何在 …
python properties decorator python-internals python-decorators
这个问题不是讨论单身人士设计模式是否可取,反模式,还是任何宗教战争,而是讨论如何以最蟒蛇的方式在Python中最好地实现这种模式.在这种情况下,我将"最pythonic"定义为表示它遵循"最小惊讶原则".
我有多个类可以成为单例(我的用例是记录器,但这并不重要).当我可以简单地继承或装饰时,我不希望在添加gumph的几个类中混乱.
最好的方法:
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass(BaseClass):
pass
Run Code Online (Sandbox Code Playgroud)
优点
缺点
m = MyClass(); n = MyClass(); o = type(n)();那时m == n && m != o && n != oclass Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class MyClass(Singleton, …Run Code Online (Sandbox Code Playgroud) 在对另一个问题的答案的评论中,有人说他们不确定functools.wraps在做什么.所以,我问这个问题,以便在StackOverflow上有一个记录,供将来参考:究竟functools.wraps做了什么?
我在看代理模式,对我而言,它似乎很像装饰器,适配器和桥模式.我误会了什么吗?有什么不同?为什么我会使用Proxy模式而不是其他模式?你过去在现实世界的项目中如何使用它们?
我有装饰器传递变量'insurance_mode'的问题.我会通过以下装饰器声明来做到这一点:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这种说法不起作用.也许有更好的方法可以解决这个问题.
def execute_complete_reservation(test_case,insurance_mode):
def inner_function(self,*args,**kwargs):
self.test_create_qsf_query()
test_case(self,*args,**kwargs)
self.test_select_room_option()
if insurance_mode:
self.test_accept_insurance_crosseling()
else:
self.test_decline_insurance_crosseling()
self.test_configure_pax_details()
self.test_configure_payer_details
return inner_function
Run Code Online (Sandbox Code Playgroud) 虽然我喜欢把自己想象成一个相当称职的Python编码器,但我从来没有能够理解的语言的一个方面就是装饰器.
我知道它们是什么(表面上),我已经阅读了有关Stack Overflow的教程,示例和问题,我理解语法,可以编写自己的,偶尔使用@classmethod和@staticmethod,但我从来没有想过使用装饰器解决我自己的Python代码中的问题.我从来没有遇到过这样的问题,"嗯......这看起来像装饰工作!"
所以,我想知道你们是否可以提供一些你在自己的程序中使用装饰器的例子,希望我会有一个"A-ha!" 一刻,得到他们.
我正在使用React学习Redux并且偶然发现了这段代码.我不确定它是否特定于Redux,但我在其中一个示例中看到了以下代码片段.
@connect((state) => {
return {
key: state.a.b
};
})
Run Code Online (Sandbox Code Playgroud)
虽然功能connect非常简单,但我@之前并不理解connect.如果我没错,它甚至不是JavaScript运算符.
有人可以解释一下这是什么,为什么用它?
更新:
事实上,react-redux它的一部分用于将React组件连接到Redux存储.
鉴于Python函数:
def a_method(arg1, arg2):
pass
Run Code Online (Sandbox Code Playgroud)
如何提取参数的数量和名称.即,鉴于我有一个func的引用,我想要返回func.[something]("arg1","arg2").
这种情况的使用场景是我有一个装饰器,我希望使用方法参数的顺序与它们为实际函数出现的顺序相同.也就是说,当我调用aMethod("a","b")时,装饰器看起来会打印出"a,b"吗?
有人可以提供一个简单的例子来演示实现装饰器的正确方法,并描述可能的有效装饰器签名中的参数是什么意思吗?
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Run Code Online (Sandbox Code Playgroud)
另外,在实现装饰器时是否应该记住哪些最佳实践注意事项?
decorator ×10
python ×7
base-class ×1
bridge ×1
functools ×1
javascript ×1
metaclass ×1
properties ×1
reactjs ×1
redux ×1
singleton ×1
typescript ×1