您如何解压缩方法参数以为其分配类属性? [英] How can you unpack method arguments to assign them class attributes?
问题描述
我经常做这种事情:
class Box:
def __init__(self):
some_setup_stuff()
def configure(
self,
color = "#ffffff",
weight = 1,
empathy = 97,
angle_x = 0,
angle_y = 0,
angle_z = 0,
displacement_x = 0,
displacement_y = 0,
displacement_z = 0
):
self.color = color
self.weight = weight
self.empathy = empathy
self.angle_x = angle_x
self.angle_y = angle_y
self.angle_z = angle_z
self.displacement_x = displacement_x
self.displacement_y = displacement_y
self.displacement_z = displacement_z
def open(self):
reveal_head()
是否存在一些整洁,小巧,相当明智的方法来将传递给类方法的参数解包"到类的属性中(同时保留明确指定的默认值)?就像,我在想,也许locals()
可以在方法的第一行中以某种方式使用,但这对我来说并不明显.
Is there some neat, small, fairly sensible way to "unpack" the arguments passed to a class method into attributes of the class (while keeping the default values specified explicitly)? Like, I'm thinking maybe locals()
could be used somehow around the first line in the method but it's not obvious to me.
所以我们最终可以得到这样的东西:
So we could end up with something a bit like this:
class Box:
def __init__(self):
some_setup_stuff()
def configure(
self,
color = "#ffffff",
weight = 1,
empathy = 97,
angle_x = 0,
angle_y = 0,
angle_z = 0,
displacement_x = 0,
displacement_y = 0,
displacement_z = 0
):
# magic possibly involving locals()
def open(self):
reveal_head()
它可以这样使用:
>>> box = Box()
>>> box.configure(empathy = 98)
>>> box.weight
1
>>> box.empathy
98
推荐答案
这里有些怪诞的方法.建立一个defaults
词典,其中包含允许的参数的默认值.在对键进行一些错误检查之后,然后用**kwargs
更新self.__dict__
:
Here's a bit of a hacky method. Build a defaults
dictionary containing the default values for your allowed parameters. Then update self.__dict__
with **kwargs
, after some error checking on the keys:
class Box:
def __init(self):
pass
def configure(self, **kwargs):
defaults = {
"color": "#ffffff",
"weight": 1,
"empathy": 97,
"angle_x": 0,
"angle_y": 0,
"angle_z": 0,
"displacement_x": 0,
"displacement_y": 0,
"displacement_z": 0
}
bad_args = [k for k in kwargs if k not in defaults]
if bad_args:
raise TypeError("configure() got unexpected keyword arguments %s"%bad_args)
self.__dict__.update(defaults)
self.__dict__.update(kwargs)
现在您可以这样做:
box = Box()
box.configure(empathy = 98)
print(box.weight)
#1
print(box.empathy)
#98
但是,如果您这样做了:
But if you did:
box.configure(wieght = 2)
#TypeError: configure() got unexpected keyword arguments ['wieght']
这篇关于您如何解压缩方法参数以为其分配类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!