Two ways to define a property

Source: Internet
Author: User

There are two ways to define a property :

    • Adorners: Applying adorners on methods
    • Static fields are: Static fields that define values as property objects in a class

Adorner mode: Apply @property adorner to ordinary method of class

New class: We know that the classes in Python have classic and modern classes, and the properties of the new class are richer than those of the classic class. (If the class is following object, then the class is a modern Class)

Class Goods (object):    def __init__ (self):        self.original_price = #普通字段        self.dicount_rate = 0.8   # Normal field    @property                    #获取属性    def price:        new_price = self.original_price * Self.dicount_rate        return New_price    @price. Setter           #方法名. Setter Modify Properties    def price (self,value):        Self.original_price = Value    @price. deleter        #方法名. deleter Delete    def price (self):        del self.original_price########### Call #########good_ojb =goods () o = good_ojb.price # automatically executes the @property decorated price method and gets the return value of the method s = good_ojb.price = 200 # automatic execution @pri Ce.setter modifies the price method and  assigns 200 to the parameter of the method print (O) print (s) Del Good_ojb.price # automatically executes the @price. The deleter-Modified price method GOOD_OJB. Price  #再次执行, found error hint: ' Goods ' object has no attribute ' Original_price '

Classic class:

# ############### Definition ###############    class Goods:    @property    def Price:        return "Wupeiqi" # ###### ######### call ############## #obj = Goods () result = Obj.price  # automatically executes @property decorated price method and gets the return value of the method

Note : The properties in the classic class have only one access, which corresponds to the method that is @property decorated

The properties in the new class are accessed in three ways and correspond to three @property, @ method names. Setter, @ Method name. Method of Deleter Modification

Since there are three kinds of access methods in the new class, we can define three methods for the same attribute according to the access characteristics of several properties: Get, modify, delete

---------------------------------------------------------------------

Static field, creates a static word with a value of the Property object

Classic and modern classes are no different when creating properties using static fields

Class Poo:                def get_bar (self):        return ' Wupeiqi '    bar = property (get_bar) obj = Poo () reuslt = obj. BAR        # Automatically calls the Get_bar method and gets the return value of the method print (REUSLT)

There are four parameters in the property's construction method

    • The first parameter is the method name , which 对象.属性 automatically triggers the execution method when called
    • The second parameter is the method name , which 对象.属性 = XXX automatically triggers the execution method when called
    • The third parameter is the method name , which del 对象.属性 automatically triggers the execution method when called
    • The fourth parameter is a string that 对象.属性.__doc__ is called, and this parameter is the description of the property
Class Foo ():

def get_bar (self):
Return (' Wupeiqi ')

# * must be two parameters
def set_bar (self, value):
Return (' Set value ' + value)

def del_bar (self):
Return (' Wupeiqi ')

BAR = Property (Get_bar, Set_bar, Del_bar, ' description ... ')

obj = Foo ()

Obj. BAR # Automatically calls the method defined in the first parameter: Get_bar
Obj. Bar= "Alex" # automatically invokes the method defined in the second parameter: Set_bar method and Passes "Alex" as a parameter
Del obj. BAR # Automatically calls the method defined in the third parameter: Del_bar method

Obj. bar.__doc__ # automatically gets the value set in the fourth parameter: Description ...

Because there are three ways to create properties for static fields, we can define three methods for the same attribute based on the access characteristics of several of their properties: Get, modify, delete

Three ways to compare @property adorners

Class Goods (object):    def __init__ (self):        # original price        self.original_price =        # discount        self.discount = 0.8    def get_price (self):        # actual price = Price * Discount        new_price = self.original_price * Self.discount        return new_price
   def Set_price (self, value):        Self.original_price = value    def del_price (self, value):        del Self.original_price    Prices = Property (Get_price, Set_price, Del_price, ' price attribute description ... ') obj = Goods () obj.         Price # Get commodity prices obj. Price = $   # modifies the original item del obj.     Price # Delete original item

Note: The Python Web Framework Django view is in the request. POST is the property that is created using the static field method

Class Wsgirequest (HTTP. HttpRequest): Def __init__ (self, environ): Script_name = Get_script_name (environ) path_info = get_path_in Fo (environ) if not path_info: # sometimes path_info exists, but is empty (e.g. accessing # th e script_name URL without a trailing slash). We really need to # operate as if they ' d requested '/'.            The amazingly nice-to-force # is the path like this, but should is harmless. Path_info = '/' Self.environ = environ self.path_info = path_info self.path = '%s/%s '% (script_name. Rstrip ('/'), Path_info.lstrip ('/')) self. META = Environ self. meta[' path_info ') = Path_info self. meta[' script_name ' = script_name Self.method = environ[' Request_method '].upper () _, Content_params = CGI.PA Rse_header (Environ.get (' Content_Type ', ')) if ' CharSet ' in CONTENT_PARAMS:TRY:CODECS.L          Ookup (content_params[' charset ')  except Lookuperror:pass else:self.encoding = content_params[' CharSet ') Self._post_parse_error = False try:content_length = Int (environ.get (' content_length ')) except ( ValueError, TypeError): content_length = 0 Self._stream = limitedstream (self.environ[' wsgi.input '), cont ent_length) self._read_started = False Self.resolver_match = None def _get_scheme (self): return SE Lf.environ.get (' Wsgi.url_scheme ') def _get_request (self): Warnings.warn (' request '. Request ' is deprecated, use ' request. GET ' or ' request. POST ' instead. ', removedindjango19warning, 2) if not hasattr (self, ' _request '): Self._request = Datastru Ctures. Mergedict (self. POST, self. Get) return self._request @cached_property def get (self): # The WSGI spec says ' query_string ' could be a        Bsent. raw_query_string = Get_bytes_from_wsgi (Self.environ, ' query_string ', ') return HTTP. Querydict (Raw_query_string, encoding=self._encoding) # ############### look here ############### def _get_post (sel f): If not hasattr (self, ' _post '): Self._load_post_and_files () return Self._post # ########### # # # Look here look here ############### def _set_post (self, post): Self._post = post @cached_property def COOKIES (sel    f): Raw_cookie = Get_str_from_wsgi (Self.environ, ' Http_cookie ', ') return Http.parse_cookie (Raw_cookie) def _get_files (self): If isn't hasattr (self, ' _files '): Self._load_post_and_files () return Self._fi Les # ############### look here ############### POST = Property (_get_post, _set_post) FILES = Property (_get_fil ES) REQUEST = property (_get_request)

Two ways to define a property

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.