Object-oriented features of Python

Source: Internet
Author: User

Object-oriented featuresfirst, the package

Python does not rely on language features to encapsulate data, but rather to achieve encapsulation by following the naming of certain data attributes or function properties. Any name that begins with a single underscore should be internal and private. Encapsulates the meaning of data hiding within the internal business logic. Python's true encapsulation is distinguished by internal and external access to the class. And it differs greatly from the private attribute of Java, whichdoes not have the mandatory rejection of external classes for private attributes . In other words, a private property that begins with a single underscore or a double underscore is just a convention. It is important to note that when we use the private properties of another module when importing, you cannot use the "*" number, only the name of the private property. Python has a meaningful level of encapsulation.

1. First Layer Package

Use a private property that begins with a single underscore. objects can be called directly using the object name . private property name.

2. Second Layer package

Use a private property that begins with a double underscore. Object cannot be called directly using the object name . private property name.  You need to precede the private property with a double underscore with the "_ class name", such as: "Object name . _ Class name . Private property name.

3.43-Layer Package

Use a custom function to provide an interface. Explicitly differentiate inside and outside, implement the encapsulation of internal business logic , and give the external program the use of custom interface functions like Java Setter and Getter methods, let the interface function return a value of the private nature. However, in the design of the program must be aware that the program at the beginning of the design should not be the private properties of the bundle version, or in the future modification or maintenance will be very painful. Only the data that really needs encapsulation needs to be encapsulated. such as the employee's salary and other important data.

        classPerson : _privateproperty="private property that begins with a single underscore"            __property="private property that begins with a double underscore"            def __init__(self, name, gender, age): Self.name=name Self.gender=Gender Self.age= AgedefReturn_property (self):returnSelf.__property            defShowinfo (self):Print(Self.name, Self.gender, self.age) person= Person ("Handy","female", 18)        #private property that starts with a single underline        Print(Person._privateproperty)#private property with double underscore, note how to call        Print(Person._person__property)

Ii. Inheritance

  Python's inheritance is very similar to C + +, where its inheritance is interpreted by the interpreter as an MRO list, which is a simple, linear sequential list of all base classes. The MRO list is constructed through a C3 Linearization algorithm to achieve this. As with Java, the final base class for all classes is Object. Inheritance is harmful in some way, and inheritance is coupling classes to classes. This greatly destroys the system's closed principle. The inheritance that is really meaningful is the inheritance of the interface type. The interface-style inheritance provided by Python.

the inheritance sequence of Python can be viewed by the class using __mro__. The Interpreter view order follows the following three rules:

1. Subclasses are checked before the parent class

2. Multiple parent classes are checked according to their order in the list

3. If there are two valid choices for the next class, select the first parent class

    classPerson :"""describe the human class"""        def __init__(self, name, gender, age): Self.name=name Self.gender=Gender Self.age= AgedefPrintinfo (self):Print("Human")    classStudent (person):"""Class of Students"""        def __init__(self, name, gender, age, school):"""when using super to invoke the constructor of the parent class, self is not allowed in the argument because Super has given self the default, and if you add self, it will give an error. And the reason for the error is that one more parameter. Using super () calls a function of the parent class to make the program more flexible.            Of course, you can also use the following coupled invocation patterns. Person.__init__ (self, name, gender, age)"""super ().__init__(name, gender, age) Self.school=SchooldefPtintinfo (self):Print(Self.name, Self.gender, Self.age, Self.school) s= Student ("Macky","female", 18,"mit") S.ptintinfo ()

Three, polymorphic

Python's polymorphism is the same as Java's polymorphism. The polymorphic concept points out how objects are accessed through their common attributes and functions, without having to consider the specific classes between them.

    classPerson :def __init__(self, Name, age): Self.name=name Self.age= Agedefbehavior (self):ifSelf.age >= 0 andSelf.age <= 18:                Print("%s is a minor."%self.name)Else:                Print("%s is an adult"%self.name)classAdult (person):Pass    classpupil (person):Pass    #A simple example of how to implement polymorphism    deffunc (obj): Obj.behavior ()#initializing adult and pupilAdult = Adult ("Xiao Ming", 3) Pupil= Pupil ("Xiao Hua", 20)    #Call the Func functionfunc (Adult) func (pupil)

Iv. Reflection

The concept of reflection was first proposed by smith in lisp and the object-oriented aspects of the results achieved. Reflection shows how an object obtains its own state during the run. If you pass an object to you, you can find out all of his abilities, which is a powerful feature. If python does not support some form of reflection functionality, dir and type built-in functions, will be difficult to work with. There are special properties like __dict__, __name__ and __doc__. What good does that reflection have? It can be defined in advance interface, interface only after the completion of the actual execution, this implementation of Plug and Play, which is actually a "late binding", you can pre-write the main logic (only define the interface), and then later to implement the interface function. This is the same as the reflection mechanism of the java, except that it is different in the form of monetization. This technology is essential in development.

The implementation of the reflection technology is based on the following four functions:

hasattr (object, name)

Determine if there is a method or property in the object that corresponds to a name string.

GetAttr (object, Name, Default=none)

Gets the property value of the object or the address of the function. Returns False when the property value of the Get object does not exist , and the function does not have a times error. If you want the function not to exist when the error can and can inform us that the function does not exist, evil can use the default parameter. The function has the same function as the object invocation property. such as:getattr (x, ' y ') <==> x.y

setattr (x, y, v)

Sets or modifies a value for the property Y of Object X, and appends the non-existent property of the SetAttr setting to the object's dictionary when the property does not exist. such as:setattr (x, y, v) <==> x.y =v

delattr (x, y)

Deletes an object's properties. such as:delattr (x, y) <==> del x.y

    classPerson :def __init__(self, name, gender, age): Self.name=name Self.gender=Gender Self.age= AgedefEating (self):Print("at dinner")        defSleep (self):Print("in bed") Person= Person ("Handy","female", 18)    #use Hasattr to determine if a property exists in an object name    Print(Hasattr (Person,"name"))#Output: True    #to get the property values of an object using GetAttr    Print(GetAttr (Person,"name"))#Output: Handy    #get the function address of an object using GetAttr    Print(GetAttr (Person,"Eating"))#output: Address of eatting ()    #Run functionGetAttr (Person,"Eating")()#output: at dinner    #using the default parameter of GetAttr    Print(GetAttr (Person,"Eatingfood","function does not exist"))#output: Function does not exist    #use SetAttr to modify a valueSetAttr (Person,"name","Lily")    Print(person.__dict__)    #appends a non-existent value to the object's dictionarySetAttr (Person,"ID","001")    Print(person.__dict__)    #Add function 1SetAttr (Person,"func",LambdaX:x+1)    Print(Person.func)Print(Person.func (10))    #Add function 2SetAttr (Person,"func",Lambdaself:self.name+"Yes, I can do this.")    Print(Person.func)Print(Person.func (person))#to delete an object's properties using DelattrDelattr (Person,"ID")    Print(person.__dict__)

Object-oriented features of Python

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.