python - Best practice: update/extend subclass class attribute -
this little curiosity. find myself updating class attribute inherited in subclass , i'd know how others deals it. know can't update them in __init__
: since it's class attribute update superclass instances well. this:
class a(object): attribute = { 1: 'a', ..., 5: 'e', } class b(a): attribute = { 1: 'a', ..., 5: 'e', 6: 'f', }
but, since follow dry principle as possible , i'd know if use more elegant way without copy , paste attribute.
as asked concrete example django forms:
class loginform(authenticationform): username = forms.emailfield(label=_('email')) error_messages = { 'inactive': _('this account inactive.'), 'invalid_login': _('please enter correct username , password. ' 'note both fields may case-sensitive.'), 'unconfirmed': _('your account not confirmed yet. please ' 'check email , follow instructions ' 'in order activate it.'), } def confirm_login_allowed(self, user): super(loginform, self).confirm_login_allowed(user) if not user.confirmed: raise forms.validationerror( self.error_messages['unconfirmed'], code='unconfirmed')
the error_messages attribute inherited django.contrib.auth.forms.authenticationform wanted add 'unconfirmed' key had copy , paste 'inactive' , 'invalid_login' keys too.
if put in __init__
every instance of subclass (b
in case), see update. time not if specify class directly:
b.attribute[6] # keyerror
one way without using __init__
to:
class b(a): attribute = a.attribute.copy() attribute.update({ 6: 'f', 7: 'g', }) print(b().attribute) # --> {1:'a', ..., 5:'e', 6:'f', 7:'g'} print(a().attribute) # --> {1:'a', ..., 5:'e'}
the point remember class's code executed created, can use normal python make adjustments.
Comments
Post a Comment