On Thu, Jun 16, 2011 at 10:35 PM, Micky Hulse <[email protected]> wrote:
> Just to clarify things for me, does attribute equal a property or method? :D
>
> I am guessing that attribute = property, so you're saying that I
> could/should do this:
>
> @property
> def separator(self):
> return ' :: '
>
No, he's saying that is ridiculous overkill for a constant attribute.
class MyModel(models.Model):
SEPARATOR = '::'
Access it with MyModel.SEPARATOR or my_model_instance.SEPARATOR
I use property() when either the setting or modification of an
attribute requires me to run actual code in order to manipulate the
supplied value into a different format. Eg, if I am storing a comma
separated list of IP addresses as strings in a database field, I don't
want to have to deal with splitting, parsing and turning it into a
list of proper objects in every different place. Instead, I supply a
property that serializes/deserializes the data as needed.
Another reason to use property() is when you remove an attribute that
is part of your public API, you can provide a property with the same
name as the attribute. Eg:
class MyModel(models.Model):
@property
def SEPARATOR(self):
if self.foo:
return '::'
return '||'
The behaviour is now dynamic, but any old code using
instance.SEPARATOR will get still work, and use the new dynamic
definition.
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.