Django的@property有什么作用? [英] What does Django's @property do?
问题描述
在Django中,什么是 @property
?
What is @property
in Django?
这是我的理解: @property
是类中获取方法值的装饰器。
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.
文档:
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)
有什么区别
推荐答案
如您所见,函数full_name返回包含人员的字符串姓氏和名字。
As you see, the function full_name returns a string with the persons first and last name.
@property
装饰器的作用是声明可以像访问它一样访问它。常规属性。
What the @property
decorator does, is declare that it can be accessed like it's a regular property.
这意味着您可以调用 full_name
,就好像它是成员变量而不是函数一样,因此像这样:
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
而不是
name = person.full_name()
您还可以这样定义一个setter方法:
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'
而不是
person.set_full_name('John Doe')
PS上面的setter只是一个示例,因为它仅适用于由两个用空格分隔的单词组成的名称。在现实生活中,您会使用更强大的功能。
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.
这篇关于Django的@property有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!