gpt4 book ai didi

python - 您如何解压方法参数来为它们分配类属性?

转载 作者:行者123 更新时间:2023-11-28 22:16:05 25 4
gpt4 key购买 nike

我经常做这种事情:

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

最佳答案

这是一个有点老套的方法。构建一个包含允许参数默认值的 defaults 字典。然后在对键进行一些错误检查后,用 **kwargs 更新 self.__dict__:

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']

关于python - 您如何解压方法参数来为它们分配类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com