我经常做这样的事情:
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
四季花海
相关分类