Detailed and django in python3 @property

django provides a built-decorator

@staticmethod\@classmethod\property

 

In OSQA in, @ property of the frequency of use is very high. Here is its use:

@property can python defined function "as" property access, providing access to more user-friendly way, and java in the setter and getter similar.

models.py as follows:

from django.db import models

class Person(models.Model):
    G=(('chen','jian'),('hong','yi'),('rt','ju'))
    gender=models.CharField(max_length=20,choices=G)

    @property
    def Gender(self):
        return self.gender

    @Gender.setter
    def Gender(self,new_value):
        self.gender=new_value

In views.py in:

from django.http import HttpResponse
from mytest.models import *
def index(request):
    print Person.objects.all()[0].Gender
    b=Person.objects.all()[0]
    b.Gender='adfasfasd'
    print b.Gender
    b.save()
    return HttpResponse(Person.objects.all()[0].Gender)

@property provides is a read-only attribute, if the property needs to be modified, then you need to define its setter.

 

 

######### python3 in

 

@staticmethod: static methods, static methods can not access instance variables or class variables, class methods actually has nothing to do with class, it's just like one of the following function, with the class itself does not matter, only nominally classified tube. 
It is associated with the class only need to call this method through the class name
If you have to pass parameters, only pass their own
@classmethod: class methods can access only class variables, instance variables can not be accessed

@property: property methods, the role of property @property method is through a method to become a static property
E.g:
Copy the code
Dog class. 1 (Object): 
2 DEF the __init __ (Self, name): 
. 3 = the self.name name 
. 4 # @Property put into a method of a static property 
. 5 DEF EAT (Self): 
. 6 Print ( 'IS eating% S% s'% (self.name, 'buns')) 
. 7 Dog D1 = (' Jack ') 
. 8 without d1.eat # (), output: Jack is eating buns
Copy the code
Copy the code
To pass the parameter # 1 
 2 Dog class (Object): 
 . 3 DEF the __init __ (Self, name): 
 . 4 = the self.name name 
 . 5 Food Self .__ = None 
 . 6 @Property 
 . 7 DEF EAT (Self): 
 . 8 Print ( '% S % S eating iS '% (the self.name, Food Self .__)) 
 . 9 
10 @ eat.setter 
. 11 DEF EAT (Self, Food): 
12 is Print (' pass parameters to be: ', Food) 
13 is Self .__ = Food Food 
Dog D1 = 14 ( 'Jack') 
15 d1.eat 
16 d1.eat = 'buns' 
. 17 d1.eat #self .__ = Food Food pass the parameter values and then performing the method of the properties
Copy the code

 

 

Excerpt from others notes

Define a class Student, have variable names name and score

1 class Student(object):  
2     def __init__(self,name,score):  
3         self.name = name  
4         self.score = score  

However, the above definition of this score is not a parameter check, which means that we can not perform the necessary parameters and error handling.

We can define the appropriate set and get member function to access the member variables score, and parameter check. As follows:

Copy the code
 1 class Student(object):  
 2     def __init__(self,name,score):  
 3         self.name = name  
 4         self.score = score  
 5     def get_score(self):  
 6         return self.score  
 7     def set_score(self,score):  
 8         if not isinstance(score, int):  
 9             raise ValueError(”invalid score!!!”)  
10         if score < 0 or score > 100:  
11             raise ValueError(”score must be between [0,100]!!!”)  
12         self._score = score  
Copy the code

The code defines the set and get functions score members. (Possible practical application, modify scores more common)

Now, we change the code argument is this:

Student = S1. 1 ()   
2 s1.set_score (9999) throws an exception where #  

The second way to achieve the above-mentioned parameter checks set function, but modified score of the code into a s1.set_score (90) from simple s1.score = 90. How do we achieve both test input parameters also makes modify the score of the code change it?

@Property is this role.

Below, we discuss the advanced features @Property Python. Simply put @Properyty is to call a member function becomes property assignment.

So with the following code:

Copy the code
 1 class Student(object):  
 2     def __init__(self,name,score):  
 3         self._name = name  
 4         self._score = score  
 5     @property  
 6     def score(self):   
 7         return self._score  
 8     @score.setter   
 9     def score(self,score):    
10         if not isinstance(score,int):  
11             raise ValueError(”invalid score!!!”)  
12         if score < 0 or score > 100:  
13             raise ValueError(”score must be between [0,100]!!!”)   
14         self._score = score  
15     @property  
16     def name(self):   
17         return self._name  
18   
19 s1 = Student(”Lily”, 90)  
20 s1.name = ”Luly”  
21 s1.score = 100  
Copy the code

Description about the above code:

  • As you may have discovered, I changed _name member variables and _score, here first and foremost to increase readability, these two variables are private. Second, analysis of the reasons given in the following errors.
  • The above code s1.name = "Luly" line will compile error AttributeError: can not set attribute, that is to say there can not directly change this, this is why? It can be seen in the code, I did not provide a name for the name of the set function, here is worth noting that, s1._name = "Lucy" is run by the. But we have said before, and assumed that the user conscious enough not to operate _xxx or __xxx such a variable name.
  • The code according to the original intention, that is the name of the class read-only attribute. score is modifiable.
  • Function is modified score on @property get a simple function that does not require any parameters (self does not need to pass value), so we can call this function, namely s1.score can. (This is the Property usefulness, the property access into a function call), which is equivalent to score add a layer package.
    • About @ score.setter function is set for member variables and functions parcel of the score. When we need to modify the value _score using score function, but as members of the same class attribute score is, for example above: s1.score = 100, essentially equivalent to s1.score (100).

      Note that this function name does not have to score, it can be any string here just to say score function is _score aspects of the package, for example, the following code: we will score changed to AA, but in this way:

  • Copy the code
     1 class Student(object):  
     2   
     3     def __init__(self,name,score):  
     4         self._name = name  
     5         self._score = score  
     6  
     7     @property  
     8     def AA(self):  
     9         return self._score  
    10     @AA.setter  
    11     def AA(self,score):  
    12         if not isinstance(score,int):  
    13             raise ValueError(“invalid score!!!”)  
    14         if score < 0 or score > 100:  
    15             raise ValueError(“score must be between [0,100]!!!”)  
    16         self._score = score  
    17     @property  
    18     def name(self):  
    19         return self._name  
    20             
    S1 = Student 21 is ( "Lily", 90)   
    22 is s1.name = "Luly"   
    23 is s1.AA where # = 100 is equivalent s1.AA (100)  
    Copy the code

    Well, the concept and usage of @Property on finished. Essentially defines a new function that they perform the set and get functions and parcel of @Property. And these same attributes as defined function to assignment.

    Possible pitfalls exist:

    The following code is a big trap, because the function is no longer a simple function, but can be directly used = to call, such as calling the above function score turned out to be s1.score = 100. This will appear below problem:

  • Copy the code
     1 class Student(object):   
     2     def __init__(self,name,score):         
     3         self.name = name      
     4         self.score = score     
     5     @property     
     6     def score(self):  
     7         return self.score   
     8     @score.setter   
     9     def score(self,score):     
    10         if not isinstance(score,int):   
    11             raise ValueError(”invalid score!!!”)    
    12         if score < 0 or score > 100:       
    13             raise ValueError(”score must be between [0,100]!!!”)      
    14         self.score = score   
    15     @property   
    16     def name(self):   
    17         return self.name   
    18     def func(self):      
    19         self.score = score   
    20   
    21 s1 = Student(”Lily”, 90)  
    22 s1.func()  
    Copy the code

    The above code has two big mistake,

    • You will find that you can not define any instance of Student, and why? First @property the score and name two member functions can be accessed as a member variable, then when defining instance, call the init function of time, self.name = name, this one, Python will be left as the self.name function calls, but we did not define the function to set the variable name, so the error message is: AttributeError: can not set attribute.
    • Well, we are going to comment out
  • 1 @property  
    2 def name(self):   
    3     return self.name  

    These two lines, then the next run or wrong, and why? Because the init function of the second line of code self.score = score, very glad that we define the set function score, then score self.score calling function when the function execution to score the last sentence self.score = score when we return They found that expression of the left or the score function calls, and so forth, eventually reached the maximum depth of recursive function to exit the program.

    In fact, here it is a good coding practices, that is, try not to let the name of the function and variable names of the same name, they can avoid these errors. So, for example, where the variable name self.score changed: self._score can avoid recursion error.

 

 
 

In OSQA in, @ property of the frequency of use is very high. Here is its use:

@property can python defined function "as" property access, providing access to more user-friendly way, and java in the setter and getter similar.

models.py as follows:

from django.db import models

class Person(models.Model):
    G=(('chen','jian'),('hong','yi'),('rt','ju'))
    gender=models.CharField(max_length=20,choices=G)

    @property
    def Gender(self):
        return self.gender

    @Gender.setter
    def Gender(self,new_value):
        self.gender=new_value

In views.py in:

from django.http import HttpResponse
from mytest.models import *
def index(request):
    print Person.objects.all()[0].Gender
    b=Person.objects.all()[0]
    b.Gender='adfasfasd'
    print b.Gender
    b.save()
    return HttpResponse(Person.objects.all()[0].Gender)

@property provides is a read-only attribute, if the property needs to be modified, then you need to define its setter.

 

 

######### python3 in

 

@staticmethod: static methods, static methods can not access instance variables or class variables, class methods actually has nothing to do with class, it's just like one of the following function, with the class itself does not matter, only nominally classified tube. 
It is associated with the class only need to call this method through the class name
If you have to pass parameters, only pass their own
@classmethod: class methods can access only class variables, instance variables can not be accessed

@property: property methods, the role of property @property method is through a method to become a static property
E.g:
Copy the code
Dog class. 1 (Object): 
2 DEF the __init __ (Self, name): 
. 3 = the self.name name 
. 4 # @Property put into a method of a static property 
. 5 DEF EAT (Self): 
. 6 Print ( 'IS eating% S% s'% (self.name, 'buns')) 
. 7 Dog D1 = (' Jack ') 
. 8 without d1.eat # (), output: Jack is eating buns
Copy the code
Copy the code
To pass the parameter # 1 
 2 Dog class (Object): 
 . 3 DEF the __init __ (Self, name): 
 . 4 = the self.name name 
 . 5 Food Self .__ = None 
 . 6 @Property 
 . 7 DEF EAT (Self): 
 . 8 Print ( '% S % S eating iS '% (the self.name, Food Self .__)) 
 . 9 
10 @ eat.setter 
. 11 DEF EAT (Self, Food): 
12 is Print (' pass parameters to be: ', Food) 
13 is Self .__ = Food Food 
Dog D1 = 14 ( 'Jack') 
15 d1.eat 
16 d1.eat = 'buns' 
. 17 d1.eat #self .__ = Food Food pass the parameter values and then performing the method of the properties
Copy the code

 

 

Excerpt from others notes

Define a class Student, have variable names name and score

1 class Student(object):  
2     def __init__(self,name,score):  
3         self.name = name  
4         self.score = score  

However, the above definition of this score is not a parameter check, which means that we can not perform the necessary parameters and error handling.

We can define the appropriate set and get member function to access the member variables score, and parameter check. As follows:

Copy the code
 1 class Student(object):  
 2     def __init__(self,name,score):  
 3         self.name = name  
 4         self.score = score  
 5     def get_score(self):  
 6         return self.score  
 7     def set_score(self,score):  
 8         if not isinstance(score, int):  
 9             raise ValueError(”invalid score!!!”)  
10         if score < 0 or score > 100:  
11             raise ValueError(”score must be between [0,100]!!!”)  
12         self._score = score  
Copy the code

The code defines the set and get functions score members. (Possible practical application, modify scores more common)

Now, we change the code argument is this:

Student = S1. 1 ()   
2 s1.set_score (9999) throws an exception where #  

The second way to achieve the above-mentioned parameter checks set function, but modified score of the code into a s1.set_score (90) from simple s1.score = 90. How do we achieve both test input parameters also makes modify the score of the code change it?

@Property is this role.

Below, we discuss the advanced features @Property Python. Simply put @Properyty is to call a member function becomes property assignment.

So with the following code:

Copy the code
 1 class Student(object):  
 2     def __init__(self,name,score):  
 3         self._name = name  
 4         self._score = score  
 5     @property  
 6     def score(self):   
 7         return self._score  
 8     @score.setter   
 9     def score(self,score):    
10         if not isinstance(score,int):  
11             raise ValueError(”invalid score!!!”)  
12         if score < 0 or score > 100:  
13             raise ValueError(”score must be between [0,100]!!!”)   
14         self._score = score  
15     @property  
16     def name(self):   
17         return self._name  
18   
19 s1 = Student(”Lily”, 90)  
20 s1.name = ”Luly”  
21 s1.score = 100  
Copy the code

Description about the above code:

  • As you may have discovered, I changed _name member variables and _score, here first and foremost to increase readability, these two variables are private. Second, analysis of the reasons given in the following errors.
  • The above code s1.name = "Luly" line will compile error AttributeError: can not set attribute, that is to say there can not directly change this, this is why? It can be seen in the code, I did not provide a name for the name of the set function, here is worth noting that, s1._name = "Lucy" is run by the. But we have said before, and assumed that the user conscious enough not to operate _xxx or __xxx such a variable name.
  • The code according to the original intention, that is the name of the class read-only attribute. score is modifiable.
  • Function is modified score on @property get a simple function that does not require any parameters (self does not need to pass value), so we can call this function, namely s1.score can. (This is the Property usefulness, the property access into a function call), which is equivalent to score add a layer package.
    • About @ score.setter function is set for member variables and functions parcel of the score. When we need to modify the value _score using score function, but as members of the same class attribute score is, for example above: s1.score = 100, essentially equivalent to s1.score (100).

      Note that this function name does not have to score, it can be any string here just to say score function is _score aspects of the package, for example, the following code: we will score changed to AA, but in this way:

  • Copy the code
     1 class Student(object):  
     2   
     3     def __init__(self,name,score):  
     4         self._name = name  
     5         self._score = score  
     6  
     7     @property  
     8     def AA(self):  
     9         return self._score  
    10     @AA.setter  
    11     def AA(self,score):  
    12         if not isinstance(score,int):  
    13             raise ValueError(“invalid score!!!”)  
    14         if score < 0 or score > 100:  
    15             raise ValueError(“score must be between [0,100]!!!”)  
    16         self._score = score  
    17     @property  
    18     def name(self):  
    19         return self._name  
    20             
    S1 = Student 21 is ( "Lily", 90)   
    22 is s1.name = "Luly"   
    23 is s1.AA where # = 100 is equivalent s1.AA (100)  
    Copy the code

    Well, the concept and usage of @Property on finished. Essentially defines a new function that they perform the set and get functions and parcel of @Property. And these same attributes as defined function to assignment.

    Possible pitfalls exist:

    The following code is a big trap, because the function is no longer a simple function, but can be directly used = to call, such as calling the above function score turned out to be s1.score = 100. This will appear below problem:

  • Copy the code
     1 class Student(object):   
     2     def __init__(self,name,score):         
     3         self.name = name      
     4         self.score = score     
     5     @property     
     6     def score(self):  
     7         return self.score   
     8     @score.setter   
     9     def score(self,score):     
    10         if not isinstance(score,int):   
    11             raise ValueError(”invalid score!!!”)    
    12         if score < 0 or score > 100:       
    13             raise ValueError(”score must be between [0,100]!!!”)      
    14         self.score = score   
    15     @property   
    16     def name(self):   
    17         return self.name   
    18     def func(self):      
    19         self.score = score   
    20   
    21 s1 = Student(”Lily”, 90)  
    22 s1.func()  
    Copy the code

    The above code has two big mistake,

    • You will find that you can not define any instance of Student, and why? First @property the score and name two member functions can be accessed as a member variable, then when defining instance, call the init function of time, self.name = name, this one, Python will be left as the self.name function calls, but we did not define the function to set the variable name, so the error message is: AttributeError: can not set attribute.
    • Well, we are going to comment out
  • 1 @property  
    2 def name(self):   
    3     return self.name  

    These two lines, then the next run or wrong, and why? Because the init function of the second line of code self.score = score, very glad that we define the set function score, then score self.score calling function when the function execution to score the last sentence self.score = score when we return They found that expression of the left or the score function calls, and so forth, eventually reached the maximum depth of recursive function to exit the program.

    In fact, here it is a good coding practices, that is, try not to let the name of the function and variable names of the same name, they can avoid these errors. So, for example, where the variable name self.score changed: self._score can avoid recursion error.

 

Guess you like

Origin www.cnblogs.com/Brin-guo/p/10962558.html