Python初始化 [英] Python initialization
问题描述
我有这个代码:
def __init __(self,a,b,c,d ...):
self.a = a
self.b = b
etc
我想用它取代:
def __init __(self,a,b,c,d ...) :
args = locals()
for args:
self .__ dict __ [key] = args [key]
这是个坏主意吗?
建立在@ ThiefMaster对的评论kwargs
:
如果你接受20个参数,要求用户通过关键字而不是位置发送参数可能更有意义:with 20参数,有一个体面的机会,有人使用您的代码将获得参数的顺序错误。
仅考虑 接受kwargs,同时拥有您想接受的键的预定义列表,如果您没有收到它们,则会引发ValueError。所以你可以使用 ** kwargs
,然后检查一切是否都存在。例如
INITIAL_ARGS = set(['a','b','c','d','e'。 ..])
/ pre>
def __init __(self,** kwargs):
如果不是INITIAL_ARGS.issubset(set(kwargs.iterkeys())):
raise ValueError类< myclass>需要20个关键字参数
只给定%d%len(kwargs))
self .__ dict __。update(kwargs)
不知道这是否比你原来的Pythonic更多或更少,但似乎它会节省一些时间后,当试图找出为什么某人使用您的代码可能会得到奇怪的错误。
I have this code:
def __init__(self, a, b, c, d...): self.a = a self.b = b etc
I'm thinking of replacing it with:
def __init__(self, a, b, c, d...): args=locals() for key in args: self.__dict__[key] = args[key]
Is this a bad idea? Are there any better ways to do this?
解决方案Building on @ThiefMaster's comment about
**kwargs
:If you are taking in 20 arguments, it might make more sense to require your users to send arguments via keyword instead of position: with 20 arguments, there is a decent chance that someone using your code will get the arguments in the wrong order.
Consider only accepting kwargs while having a predefined list of keys you want to accept and raising a ValueError if you don't receive them. So you could use
**kwargs
and then check that everything is there. E.g.INITIAL_ARGS = set(['a','b','c','d','e'...]) def __init__(self, **kwargs): if not INITIAL_ARGS.issubset(set(kwargs.iterkeys())): raise ValueError("Class <myclass> requires 20 keyword arguments" "only given %d" % len(kwargs)) self.__dict__.update(kwargs)
Not sure whether this is more or less Pythonic than your original, but it seems like it would save a ton of time later on when trying to figure out why someone using your code might be getting strange errors.
这篇关于Python初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!