hey,
question, in how far is it a good idea to use ‘@property’ in your View to set the model ?
Because @proprty is a good get/set system.
But setting the model seams like a complex action and I don’t know in how far this fits in the idea of @prototype.
Another option is to create a ‘set_model(self, model)’ method.
But then it feels kinda stupid since it is a setter but not using a ‘@property’ and uses the word ‘set’.
Any idea’s on this ? Other good ways of naming this ? ‘apply_model()’ ?
thanks !
class MyModel(object):
def __init__(self):
pass
class MyView(object):
def __init__(self):
self._model = None
@property
def model(self):
return self._model
@model.setter
def model(self, value):
self._model = value
# complex code
self.update()
view = MyView()
model = MyModel()
view.model = model
The main hard and fast rules are:
- Property get-sets can’t have sideffects
- get-sets have to be cheap and fast - don’t use get or set for something that takes a long time, or which might fail because of a dropped net connection or similar
- get-sets should be symmetrical: if you do a = 1, a = 2 , a=1 then the state of the object at the end should be identical to the way it was at the beginning of the series.
But meaning this that a getter and setter should only affect a variable is not the case ?
I meaning a getter and setter can be hooked to gui widgets
self.message = 'hello'
will set / get the content of a ‘message_lineEdit’ widget
This action is stable and fast.
But is this considered as a ‘cheap’ action ?
That’s fine - you have to set the widget some time.
On the other hand you would not want to have a get property which issued a perforce command every time the object’s values were queried - that would flood your lan with individual queries that would slow you and everybody else down.
The big advantage of properties in MVC is that they let you decouple the program logic:
‘Hey, widget 123 - your underlying value is now X’
from the display logic:
‘If my value is less than zero, set my background color to red and display “invalid”; if it’s exactly zero set my background color to gray, and if it’s larger than 0 set it to green. For all values >= 0 display my value in a float field’
in the very minimal case of
Class X(object):
@property
def val(self):
return self._val
@val.getter
def set_val(self, val):
self._val = val
That’s only worth doing if you know you will be putting more complex behavior on ‘val’ in the future, or if you want to make it read-only or write-only. In python the difference between fields and properties is much less important than it would be in other languages, so writing property boilerplate isn’t worth it until you actually need to trigger some other action on property gets or sets.