问题
I do this type of thing a lot:
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()
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()
And it could be used like this:
>>> box = Box()
>>> box.configure(empathy = 98)
>>> box.weight
1
>>> box.empathy
98
回答1:
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)
Now you can do:
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']
来源:https://stackoverflow.com/questions/52429772/how-can-you-unpack-method-arguments-to-assign-them-class-attributes