Reproduced Python uses the @property adorner--getter and setter methods to become properties

Source: Internet
Author: User

Original sticker: Why Python does not need getter and setter

Getter and setter are widely used in Java. A good Java programming guideline is to set all properties to private, and write getter and setter functions for the properties for external use. The benefit of this is that the specific implementation of the attribute is hidden, and when changes are needed in the future, only the getter and setter can be modified, rather than modifying all references to this attribute in the code. The possible modifications are:

    • To hit a log when getting or setting properties
    • When setting properties, check for value pairs
    • When settings occur, modify the value of the setting
    • Calculate values dynamically when you get a property

It is a lot of benefits, getter and setter for variable access provides a flexible way.

However, the situation in Python is different because the mechanism of object property access is different. The reason why you need to write getter and setter for variables in Java is that when we write such an expression Person.name to get the name property of a person object, the meaning of the expression is fixed, which is to get the property, and not to trigger a function call. But for Python, the expression might be to get a property directly, or it might call a function. This depends on how the person class is implemented. In other words, Python's object property access syntax naturally provides getter and setter functionality.

Because of this distinction, it is not necessary for us to write getter and setter for each object's properties in Python. At the very beginning, we always use attributes as a directly accessible property. We can modify this property to a function-triggered property when we need some control over the access to this attribute later on. Before and after the modification, the code calling this object property is not modified, because the same syntax is used to access the property.

 Public classstudent{PrivateString number;//Students ' study number        PrivateString name;//Student Name        Private intGrade//Student Achievement         PublicStudent () {} PublicString GetNumber () {//get the number with Get method ( same as below)            returnNumber ; }           Public voidSetnumber (String number) {//set the school number with set method ( same as below)             This. number=Number ; }           PublicString GetName () {returnname; }           Public voidsetName (String name) { This. name=name; }           Public intGetgrade () {returngrade; }           Public voidSetgrade (intgrade) {               This. grade=grade; }       Public Static voidMain (String agrs[]) {Student St=NewStudent (); St.setnumber ("010112233"); St.setname ("Xiao Ming"); St.setgrade (100); System.out.println ("Study Number:" +st.getnumber () + "," + "Name:" +st.getname () + "," + "Score:" +st.getgrade () + ". "); }  }  

When a setter is used to change the value of a data member, the operation must be triggered by the object itself.
When you use public to change the value of a data member, the operation can be triggered by any object
This is an object-oriented package, in short, its own data members, only visible to themselves, but also only their own to change its value

The encapsulation of the object,
Private is accessible only to the object itself, and not to any other object, including its subclasses and parent classes. Security is high, and other objects can only get or set the private property of the original object through its public method, Set,get.
Public other objects can be accessed, and security is not high.

In Python

You can use the @property adorner to turn a directly accessed property into a function-triggered property. As shown below, the code before using @property is

class Person :     def __init__ (self, name):         == person ("Tom")>>>print(person.name )
Tom

Using @property

classPerson :def __init__(self, name): Self.name=name @property#Getter Method    defname (self):returnself._name @name. Setter#properties can be constrained in setter methods, non-STR will catch a type error    defname (self,name):if  notisinstance (name, str):RaiseTypeError ("expected a string") Self._name=NAMEP= Person ('Tom')>>>Print(p.name) Tom>>>P1 = person (123) typeerror:expected A string

can also only give getter method, not write setter method, equivalent to write protection of parameters

classPerson (object):def __init__(self,age): Self.age=Age @propertydefAge (self):returnself._age @age. SetterdefAge (self,age): Self._age=Age @propertydefBirth (self):return2017-SELF._AGEP= Person (20)>>>Print(p.age)20>>>Print(P.birth)1997>>>p.birth = 1997Attribute Error #birth不存在setter方法

Reproduced Python uses the @property adorner--getter and setter methods to become properties

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.