1 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
這是一個(gè)有點(diǎn)hacky的方法。構(gòu)建一個(gè)defaults包含允許參數(shù)默認(rèn)值的字典。然后更新self.__dict__與**kwargs,在按鍵上的一些錯(cuò)誤檢查后:
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)
現(xiàn)在你可以這樣做:
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']
添加回答
舉報(bào)