我经常做这种事情:
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()
可以在该方法的第一行中以某种方式使用,但这对我来说并不明显。
所以我们最终可以得到这样的东西:
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
答案 0 :(得分:4)
这里有些不讲究方法。构建一个defaults
字典,其中包含允许的参数的默认值。在对密钥进行一些错误检查之后,用self.__dict__
更新**kwargs
:
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
但如果您这样做:
box.configure(wieght = 2)
#TypeError: configure() got unexpected keyword arguments ['wieght']