我经常做这种事:
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发布于 2018-09-20 16:56:48
这是一个有点麻烦的方法。生成包含所允许参数的默认值的defaults字典。然后,在对键进行一些错误检查之后,使用**kwargs更新**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']https://stackoverflow.com/questions/52429772
复制相似问题