开发者

Any reason not to modify another class's variables?

开发者 https://www.devze.com 2023-01-06 07:02 出处:网络
Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example,

Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example,

MyForm(Form):
    username = Field(name=None, widget=MyWidget(args))

The field name would become "username". However, this can't be established until the form is constructed. Would it be so awful to set the field.name attribute inside the form initializer, but after the field has already been constructed?

Similarly, would it be so awful to set some field.widget.xxx attributes inside the form initializer to "pass in" some variables that are used in 开发者_如何学运维various functions inside the widget class? Or should I explicitly pass them in to each and every function call? Why?


Some OO purists might perhaps object, but IMHO there is really no problem in setting public attributes in instances of other classes -- worst case, if later on you find that instance needs to take some action when certain attributes are set, you'll just turn the attribute into a property, so that a "setter method" is automatically called when the attribute is assigned to (just make sure to always use new style classes -- e.g. by inheriting from object when a class would otherwise have no bases -- so that property works properly when you need it!-).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号