对我来说看起来不错,我很想重写为:
class User(object):
def __init__(self, arg1, arg2, **traits):
self.arg1 = arg1
self.arg2 = arg2
self.traits = traits
如果你真的想要,如果找不到属性,你可以覆盖以回退到特征字典:
def __getattr__(self, name):
return self.traits[name]
例子:
>>> u = User(1, 2, email='something')
>>> y = User(1, 2, email='bob', telno='999')
>>> u.arg1, u.arg2, u.email
(1, 2, 'something')
>>> y.arg1, y.arg2, y.email, y.telno
(1, 2, 'bob', '999')
>>> y.arg1, y.arg2, y.email, y.something
Traceback (most recent call last):
File "<pyshell#105>", line 1, in <module>
y.arg1, y.arg2, y.email, y.something
File "/home/jon/adfafasdf.py", line 7, in __getattr__
return self.traits[name]
KeyError: 'something'
因此,您可能希望将其作为更明智的错误,并更改为:
def __getattr__(self, name):
try:
return self.traits[name]
except KeyError as e:
raise AttributeError() # with suitably formatted string