Python data structures and algorithms-object-oriented and python object-oriented

Source: Internet
Author: User

Python data structures and algorithms-object-oriented and python object-oriented

As mentioned above, Python is an object-oriented programming language. The most important feature of object-oriented programming language is to allow programmers to create classes to build data models to solve problems.

We used the logic provided by the abstract data type to describe the data object (its state) and function (its method ). by constructing classes to implement abstract data types, a programmer can take advantage of abstract processing and provide detailed practical information to solve the problem. when we want to implement an abstract data type, we will build a new class.

Address: Workshop.

One Score class

The following example shows a user-defined class that implements abstract data types:Fraction(Score). We already know that Python provides us with a large number of classes. There are many data objects that can help us to build the score type as appropriate.

A score, for example, 3/5, contains two parts. The numerator can be any integer. denominator, and can be any integer other than 0.

 FractionClass method should be ableFractionObjects can be calculated as other values. We need to perform addition, subtraction, multiplication, and Division operations between scores. Further, all methods should return the simplest score.

In Python, there are still some methods to define the name of a class, similar to defining a function, for example,

class Fraction:   #the methods go here

Provides a framework for defining methods. The first method is the constructor provided by all classes. The constructor defines the method for creating classes.Score objectIn Python, the constructor uses _ init _ (surrounded by two underscores ).init), As follows:

Listing 2

class Fraction:    def __init__(self,top,bottom):        self.num = top        self.den = bottom

Note that the parameter list contains three parameters :(self,top,bottom).selfIs a special parameter that references the object itself. it is usually used as the first parameter; however, it never transmits a value during the call. as mentioned before, the score contains two parts: numerator and denominator ). markself.numThe constructor is definedfractionThe object hasnumInternal data objects. Likewise,self.denThis is also a similar purpose.

To implementFractionClass, we need to call the constructor. then pass the parameter through the class name (note that we never directly call__init__). For example:

myfraction = Fraction(3,5)

Create a score objectmyfractionIndicates the score of 3/5.


The next step is to implement the abstract data type. First, realize that when we want to outputFractionObject.

>>> myf = Fraction(3,5)>>> print(myf)<__main__.Fraction instance at 0x409b1acc>

fractionObject,myfDoes not know how to respond to the output operation.printThe function needs to convert the object to the output string format. This is the only choice.myfThe actual address reference of the variable (its own address) must be displayed. This is not what we want.

There are two ways to solve the problem. One is to define oneshowYou can setFractionThe object is printed as a string, as shown in Listing 3.FractionObject, we can let it output itself, in other words, print itself according to the appropriate format. Unfortunately, this usually does not work. To make the output work normally, we must tellFractionClass to convert itself into a string format.

Listing 3

def show(self):     print(self.num,"/",self.den)>>> myf = Fraction(3,5)>>> myf.show()3 / 5>>> print(myf)<__main__.Fraction instance at 0x40bce9ac>

In Python, all classes provide but are not applicable to standard methods. One of them,__str__Is a method to convert an object to a string. the default implementation of this method is to return the address of the class instance in string format. we must provide a "better" implementation for this method. let's talk about this new method.Heavy LoadPreviously, or redefined the behavior of the method.

To achieve this, we simply define a name__str__And provide the implementation, for example, Listing 4. In addition to using special parametersOther than selfNo other information is required. Pay attention to different implementation methods in the function.

Listing 4

def __str__(self):    return str(self.num)+"/"+str(self.den)>>> myf = Fraction(3,5)>>> print(myf)3/5>>> print("I ate", myf, "of the pizza")I ate 3/5 of the pizza>>> myf.__str__()'3/5'>>> str(myf)'3/5'>>>

We canFractionClass covers many other methods. Some of the most important operations are basic arithmetic operations. We can create twoFractionObject, and use the "+" symbol to add them. Then, if we add the two scores, we get:

>>> f1 = Fraction(1,4)>>> f2 = Fraction(1,2)>>> f1+f2Traceback (most recent call last):  File "<pyshell#173>", line 1, in -toplevel-    f1+f2TypeError: unsupported operand type(s) for +:          'instance' and 'instance'

If you carefully observe the error message, you will find that the "+" operator cannot be understood.FractionOperation.

We canFractionClass provides an overloaded addition function. In Python, this method is called__add__Two parameters are required at the same time. The first parameter,selfThe second parameter is another operand. For example,

f1.__add__(f2)

WhenFractionf1AddFraction f2. Can be written as a standard form:f1+f2.

The two scores must have the same denominator before they can be directly added. The simplest way to make them have the same denominator is to share the points. The specific implementation is as follows: Listing 5. The addition function returns a newFractionObject.

Listing 5

def __add__(self,otherfraction):     newnum = self.num * otherfraction.den + self.den*otherfraction.num     newden = self.den * otherfraction.den     return Fraction(newnum,newden)
>>> f1=Fraction(1,4)>>> f2=Fraction(1,2)>>> f3=f1+f2>>> print(f3)6/8>>>

The above addition function seems to achieve what we expect, but it can be more perfect. note that 6/8 is the correct result, but it is not displayed in the form of the simplest item. the best expression is 3/4. to make our results the simplest form of items, we need an auxiliary function to simplify the score. this function can be used to obtain the maximum common divisor, or GCD. you can simplify the score by using the maximum common divisor of the numerator and denominator.

The most famous Algorithm for calculating the maximum common number is the number Euclid algorithm. I will not elaborate on the principle. It is very simple. The implementation is as follows:

>>> def gcd(m, n):    while m % n != 0:        oldm = m        oldn = n        m = oldn        n = oldm % oldn    return n>>> print gcd(20, 10)10

In this way, we can simplify any score. The Code is as follows: (Listing 6 ).

Listing 6

def __add__(self,otherfraction):    newnum = self.num*otherfraction.den + self.den*otherfraction.num    newden = self.den * otherfraction.den    common = gcd(newnum,newden)    return Fraction(newnum//common,newden//common)
>>> f1=Fraction(1,4)>>> f2=Fraction(1,2)>>> f3=f1+f2>>> print(f3)3/4

OurFractionThe object now has two very important methods, as shown in. Some of our instance classes need to be upgraded.FractionThe method is: allow two scores for comparison. Suppose we have twoFractionObject,f1Andf2.f1==f2Will getTrueIf they point to the same object, even if the denominator of the numerator is the same, but the conditions are not met, they are still not equal. This is calledShallow equality(For example ).

We can createDeep equality(For example)-judge by equal value, different from reference-overwrite__eq__Method.__eq__Is another standard method that exists in all classes.__eq__When the values of two objects are equalTrueOtherwise, returnFalse.

InFractionClass, we implement__eq__The general comparison method is used to compare the score (see Listing 7). It is worth noting that there are other methods that can be covered. For example,__le__Method provides the function of less than or equal.

Listing 7

def __eq__(self, other):    firstnum = self.num * other.den    secondnum = other.num * self.den    return firstnum == secondnum

CompleteFractionThe class code is as follows:

def gcd(m,n):    while m%n != 0:        oldm = m        oldn = n        m = oldn        n = oldm%oldn    return nclass Fraction:     def __init__(self,top,bottom):         self.num = top         self.den = bottom     def __str__(self):         return str(self.num)+"/"+str(self.den)     def show(self):         print(self.num,"/",self.den)     def __add__(self,otherfraction):         newnum = self.num*otherfraction.den + \                      self.den*otherfraction.num         newden = self.den * otherfraction.den         common = gcd(newnum,newden)         return Fraction(newnum//common,newden//common)     def __eq__(self, other):         firstnum = self.num * other.den         secondnum = other.num * self.den         return firstnum == secondnumx = Fraction(1,2)y = Fraction(2,3)print(x+y)print(x == y)

Running result:

7/6
False

 


The characteristics of object-oriented programming language can still be summarized by "program = Data Structure + algorithm ".

Program = Data Structure + algorithm is definitely applicable to object-oriented programming languages ~~~ This point of view is the same as that of the elder brother upstairs.
In addition, I personally think that the data structure + algorithm is the most basic method to solve the logic needs of the program, and I think it is the only method.
Object-oriented is the encapsulation of the underlying data structures and algorithms relative to programmers (this may be difficult to understand. If you have enough people for the target audience, I believe you will understand it immediately ), of course, I focus on the "relative to the programmer". When writing, programmers do not have to consider their underlying data structures and algorithms. They only need to write their own layers.
He still uses the data structure + algorithm when writing this layer of program. If someone performs secondary development on him, then he becomes the underlying layer of the secondary development. The secondary development personnel still use the data structure + algorithm to solve their own problems.
Let's say a few more ~~~ This is the difference between object-oriented and process-oriented. process-oriented is like the core of the earth, while process-oriented is like the break generation of each layer of the earth's rock layers, in the last sentence, object-oriented is actually a process-oriented encapsulation. The process-oriented and object-oriented are not contradictory but intertwined.

Data structures and algorithms-object-oriented C ++ Design Model

What I want to say is that if you are a student, it is very difficult to select C ~, Prepare for it ~ When will the two books be published? The content in the two books is similar, especially from algorithms ~

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.