Python装饰器自动定义__init__变量 [英] Python decorator to automatically define __init__ variables
问题描述
我已经厌烦了在我的 __ init __
函数中重复输入相同的,重复的命令。我想知道我是否可以写一个装饰师为我做的工作。以下是我的问题示例:
I've got fed up of continually typing the same, repetitive commands over and over again in my __init__
function. I was wondering if I could write a decorator to do the work for me. Here's an example of my question:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
我可以自动将传递给函数的所有参数都变成具有相同名称的实例变量?例如:
Is there some way in which I can automatically have all arguments passed into the function become instance variables with the same names? For example:
class Point:
@instance_variables
def __init__(self, x, y):
pass
其中 @instance_variables
将自动设置 self.x = x
和 self.y = y
。我怎么能这样做?
谢谢!
Where @instance_variables
would automatically set self.x = x
and self.y = y
. How could I do this?
Thanks!
编辑:我应该提到我使用CPython 2.7。
I should mention that I use CPython 2.7.
推荐答案
这是我第一次尝试装饰:
Here is my first try at the decorator:
def instanceVariables(func):
def returnFunc(*args, **kwargs):
selfVar = args[0]
argSpec = inspect.getargspec(func)
argumentNames = argSpec[0][1:]
defaults = argSpec[3]
if defaults is not None:
defaultArgDict = dict(zip(reversed(argumentNames), reversed(defaults)))
selfVar.__dict__.update(defaultArgDict)
argDict = dict(zip(argumentNames, args[1:]))
selfVar.__dict__.update(argDict)
validKeywords = set(kwargs) & set(argumentNames)
kwargDict = {k: kwargs[k] for k in validKeywords}
selfVar.__dict__.update(kwargDict)
func(*args, **kwargs)
return returnFunc
这里是一个例子:
class Test():
@instanceVariables
def __init__(self, x, y=100, z=200):
pass
def printStr(self):
print(self.x, self.y, self.z)
a = Test(1, z=2)
a.printStr()
>>> 1 100 2
这篇关于Python装饰器自动定义__init__变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!