Python in @property and @classmethod and @staticmethod

Source: Internet
Author: User

Foreplay

First of all, we must first understand what the various components of a class should be called.

-Note: It may not be the same.

   

About @property

As the name implies: it means ' attributes '.

Role:

1: Using it you will turn the class method into a class property. And is a read-only property.

2: It will re-implement getter and setter methods.

Look at the code:

  

classPerson :def __init__(self,first_name,last_name): Self.first_name=first_name Self.last_name=last_name @propertydeffull_name (self):return('%s?? %s'%(self.first_name,self.last_name))#usage#instantiating a Class objectperson = person ('Dog','Ride')#Call the field below the classPrint(Person.first_name)Print(Person.last_name)#call the method under the class that adds a property adorner. Print(Person.full_name)#no parentheses required!!! Because I have the property.#Output Result:#Dog#Ride#A dog?? Ride#The field assigns a value to see if it is possible. Person.first_name ='RI'Person.last_name='Dog Land'Print(Person.full_name)#output result: Ri?? Dog Land#Assigning a value to a propertyPerson.full_name ='Gougou'#Traceback (most recent):#File "/property.py", line Notoginseng, in <module>#person.full_name = ' ff '#Attributeerror:can ' t set attribute
# This validates its read-only property.

Because we changed the method by adding @property to the property. (So here we can call the property by calling the static property method)

But, the property is read-only!!! You cannot set this property to a different value.

A second function

code example:

 fromDecimalImportDecimal#################################################classFees (object):     #----------------------------------------------------------------------    def __init__(self):"""Constructor"""Self._fee=None#----------------------------------------------------------------------    defGet_fee (self):"""Return the current fee"""        returnSelf._fee#----------------------------------------------------------------------    defSet_fee (self, value):"""Set the fee"""        ifisinstance (value, str): Self._fee=Decimal (value)elifisinstance (value, Decimal): Self._fee=Value
  Fee = property (get_fee, set_fee)

>>> f = Fees ()
>>> F.set_fee ("1")
>>> F.fee
Decimal (' 1 ')
>>> F.fee = "2"
>>> F.get_fee ()
Decimal (' 2 ')

When we use an attribute function in this way, it allows the fee property to set and get the value itself without breaking the original code. Let's use the property decorator to rewrite this code to see if we can get a property value that is allowed to be set.

1  fromDecimalImportDecimal2  3 #################################################4 5 classFees (object):6     """"""7  8     #----------------------------------------------------------------------9     def __init__(self):Ten         """Constructor""" OneSelf._fee =None A   -     #---------------------------------------------------------------------- - @property the     deffee (self): -         """ - The fee property-the Getter -         """ +         returnSelf._fee -   +     #---------------------------------------------------------------------- A @fee. Setter at     deffee (self, value): -         """ - The setter of the fee property -         """ -         ifisinstance (value, str): -Self._fee =Decimal (value) in         elifisinstance (value, Decimal): -Self._fee =value to   + #---------------------------------------------------------------------- - if __name__=="__main__": thef =Fees () *  $ #The code above demonstrates how to create a setter method for the fee property. You can use a # decorator called @fee.setter to decorate the second method name is also the fee method to implement this. The setter is called when you do the following:Panax Notoginseng  ->>> f =Fees () the>>> F.fee ="1"
@fee. Setter

If you want to use the del command for properties, you can use the @fee. Deleter Create another adorner to decorate the same name function to achieve the same effect of deletion.

About @classmethod and @staticmethod

In general, to use a method of a class, you need to instantiate an object before calling the method.

Instead of using @staticmethod or @classmethod, you can call it without instantiating it, directly from the class name. Method Name ().

This facilitates organizing the code, putting some functions that should belong to a class into that class, while facilitating the cleanliness of the namespace.

Since both @staticmethod and @classmethod can be called directly from the class name. Method Name (), what's the difference between them?

In terms of their use,

    • @staticmethod does not need to represent the self of its own object and the CLS parameters of its own class, just as with a function.
    • @classmethod also does not require the self parameter, but the first parameter needs to be a CLS parameter that represents its own class.

If you want to invoke some of the property methods of this class in @staticmethod, you can only direct the class name. The name of the property or class. Method name.

and @classmethod, because it holds the CLS parameter, can invoke the class's properties, class methods, instantiate objects, and so on, avoiding hard coding.

@property and @classmethod and @staticmethod in Python

Related Article

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.