Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

python - What does Django's @property do?

What is @property in Django?

Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method.

But, as I understand it, I can just call the method like normal and it will get it. So I am not sure what exactly it does.

Example from the docs:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)

What is the difference of if it is there vs if it isn't?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you see, the function full_name returns a string with the persons first and last name.

What the @property decorator does, is declare that it can be accessed like it's a regular property.

This means you can call full_name as if it were a member variable instead of a function, so like this:

name = person.full_name

instead of

name = person.full_name()

You could also define a setter method like this:

@full_name.setter
def full_name(self, value):
     names = value.split(' ')
     self.first_name = names[0]
     self.last_name = names[1]

Using this method, you can set a persons full name like this:

person.full_name = 'John Doe'

instead of

person.set_full_name('John Doe')

P.S. the setter above is just an example, as it only works for names that consist of two words separated by a whitespace. In real life, you'd use a more robust function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...