# This is a learning note for the Liaoche teacher Python tutorial
1. Overview
@property Allows you to call "method" as "property"
# method source Code
Class Student (object):
def get __ score (self):
Return Self.__score
def set __ score (self, value):
If not isinstance (value, int):
Raise ValueError (' score must is an integer! ')
If value < 0 or value > 100:
Raise ValueError (' score must between 0 ~ 100! ')
Self.__score = value
# Add @property
Class Student (object):
@property # @property : Turns a getter method into a property
DEF score (self):
Return Self.__score
@score. Setter # @score. Setter : Put a Setter method becomes a property
DEF score (self, value):
If not isinstance (value, int):
Raise ValueError (' score must is an integer! ')
If value < 0 or value > 100:
Raise ValueError (' score must between 0 ~ 100! ')
Self.__score = value
Attention:
the two methods defined above score , in the past @property and the @score. Setter , it becomes a score property.
The function name is not very meaningful here, it is just for the sake of conversion to properties after we call.
through dir () , compared with two code instance , it is easy to see how the changes to the properties
used a @property after, can not be arbitrarily to instance Add Property Now .
Like the code above. S.name= ' Bart ', will be an error.
2. Example
1 , please use @property to a Screen Object Plus width and the Height property, and a read-only property resolution :
#-*-Coding:utf-8-*-
Class screen (object):
@property
def width (self):
Return __width
@width. Setter
def width (self,value):
Self.__width=value
@property
def height (self):
Return __height
@ height. Setter
def height (self,value):
Self.__height=value
@property
def resolution (self):
Self.__resolution=self.__width * Self.__height
Return self.__resolution
Test
s = screen ()
S.width = 1024
S.height = 768
Print (' Resolution = ', s.resolution)
if s.resolution = = 786432:
Print (' Test pass! ')
Else
Print (' Test failed! ' ) )
Python Learning note __7.2 using @property