Python three self-embellished features and usage (@property, @staticmethod, @classmethod)

Source: Internet
Author: User

This essay only records my understanding of these three decorators and there may be inaccuracies in the area, please note.

Property Decorator

Function: The property decorator controls the binding and acquisition of the properties of a class, typically by adding a validation type to a property.

It is more convenient and quick to point out the attribute value directly through an instance, such as Student.age in example three:

Example one:

Error effect:

Class Student (object): Age    = 20student = Student () print (student.age)  #打印结果为20student. age= "20"  # Properties that should not be bound to strings

To avoid the behavior, change the code to:

Example two:

Class Student (object):    def __init__ (self):        self._age = None    def age_getter (self):   #返回属性值        return Self._age    def age_setter (self, Age):  #设置属性值        if isinstance (age, str) and Age.isdigit ():   #验证绑定属性的类型 Age            = Int.           If Isinstance (age, Int.):            Self._age = age        Else:            raise ValueError ("Age is illegal ")  #如果不能转换类型则抛出错误student =student () student.age_setter (" 5 ")  #绑定属性为字符串5print (Student.age_getter ())   print result to 5,int format

The above code solves the problem of the property binding type error, but is not convenient enough, Python's own properties decorator can help to decorate the code, as follows:

Example three:

Class Student (object):    def __init__ (self):        self._age = None    @property  #装饰age函数, you can directly use the age function as an attribute. Bind attribute value directly by equal sign    def age (self):        return self._age    @age. Setter #通过setter设置age的属性, function internal write validation Rule Def age (self    , Age):        if Isinstance (age,int):            self._age =age            return        if Isinstance (AGE,STR) and Age.isdigit (): Age            = Int.            Self._age = age-        else:            raise ValueError ("Age is illegal")    @age. Deleter  # Deleter is the Delete attribute method    def age (self):        del self._agestudent =student () student.age = "All" Print (student.age) # del student.age# Print (Student.age)

Staticmethod Decorator

Function: To separate the decorated function from the class, the function cannot access the properties of the class, it is simply understood that the function can be interpreted as a separate function, not allowed to use self.

Staticmethod is that the decorated function is not related to the class, the function cannot use the self to pass the parameter, it needs to pass the same parameter as the normal function.

Role:
Restricted namespaces, although this function is a normal function, but only in this class can use
Code readability. Static methods do not require the self parameter
About memory. The method is not instantiated for each instance.
Controls the static method inside the class. Otherwise, put the function outside the class by changing the implementation method

Example four:

Class Dog (object):    def __init__ (self,name):        self.name = name    @staticmethod    def Eat (Name,food):        Print ("%s is eating%s"% (Name,food)) d = Dog ("Tom") D.eat ("Tom", "Bun") #通过对象调用方法Dog. Eat ("Jerry", "noodles") #通过类调用方法

Classmethod decorators, class decorators

Example five:

Class Dog (object):    name= "Jerry"    def __init__ (self,name):        self.name = name    @classmethod    def Eat ( Self):        print ('%s is eating%s '% (self.name, ' food ') ' Def talk (' self ')    :        print ("%s is talking"% self.name) d = Dog ("Tom") D.eat () dog.eat ()

A method of Factory mode
class Method can be used to create some preprocessed instances of a class .
Class methods can only find class variables and cannot access instance variables.
So the name here is Jerry, not the instanced Tom .

Python three features and use of the adorner (@property, @staticmethod, @classmethod)

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.