我做了一个修饰器,用来确保传递给构造函数的关键字参数是正确/预期参数。守则如下:
from functools import wraps
def keyargs_check(keywords):
"""
This decorator ensures that the keys passed in kwargs are the onces that
are specified in the passed tuple. When applied this decorate will
check the keywords and will throw an exception if the developer used
one that is not recognized.
@type keywords: tuple
@param keywords: A tuple with all the keywords recognized by the function.
"""
def wrap(f):
@wraps(f)
def newFunction(*args, **kw):
# we are going to add an extra check in kw
for current_key in kw.keys():
if not current_key in keywords:
raise ValueError(
"The key {0} is a not recognized parameters by {1}.".format(
current_key, f.__name__))
return f(*args, **kw)
return newFunction
return wrap使用此装饰器的示例如下:
class Person(object):
@keyargs_check(("name", "surname", "age"))
def __init__(self, **kwargs):
# perform init according to args使用上面的代码,如果开发人员传递像"blah“这样的关键arg,它将抛出一个异常。不幸的是,如果我定义以下内容,我的实现在继承方面有一个重大问题:
class PersonTest(Person):
@keyargs_check(("test"))
def __init__(self, **kwargs):
Person.__init__(self,**kwargs)
因为我将kwargs传递给超类init方法,所以我将得到一个异常,因为"test“不是在传递给超类的装饰器的元组中。有没有办法让在超类中使用的装饰师知道额外的关键字?或者更好的活动,有什么标准的方法来实现我想要的吗?
更新:当开发人员传递错误的kwarg时,我更感兴趣的是自动化抛出异常的方式,而不是使用kwargs而不是args这一事实。我的意思是,我不想编写检查每个类中传递给方法的args的代码。
发布于 2009-09-18 20:26:48
你的装潢师是不必要的。装饰器唯一不能用标准语法完成的事情是防止关键字args吸收位置参数。因此
class Base(object):
def __init__(name=None,surname=None,age=None):
#some code
class Child(Base):
def __init__(test=None,**kwargs):
Base.__init__(self,**kwargs)这样做的优点是,kwargs在Child中不包含test。问题是,您可以使用像c = Child('red herring')这样的调用来处理它。我是修正了python3.0。
您的方法的问题是,您正在尝试使用一个装饰器来完成宏的工作,这是非unpythonic的。唯一能得到您想要的东西是修改最内部函数的局部变量(代码中的f,特别是kwargs变量)。您的装饰人员如何知道包装器的内部,它如何知道它调用了一个超类?
https://stackoverflow.com/questions/1446555
复制相似问题