Python Phase Summary II

Source: Internet
Author: User

First, the object-oriented python
    • class: used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.

    • Class variables: class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.

    • data members: class variables or instance variables are used to manipulate the data related to the class and its instance objects.

    • method Overrides: if the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method, also known as the override of the method.

    • instance variable: A variable defined in a method that acts only on the class of the current instance.

    • inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object.

    • instantiation: Creates an instance of a class, the concrete object of the class.

    • method: a function defined in a class.

    • object: An instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.

Example

Here is a simple example of a Python class:

to create an instance object of a class

The instantiation class is typically used in other programming languages with the keyword new, but in Python there is no such keyword, and the instantiation of the class is similar to how the function is called.

The following uses the names of the classes Gascar and Eleccar to instantiate and accept parameters through the __init__ method.

" to create the first object of a Gascar class " gcar=gascar ("BMW") Gcar.fill_fuel (50.0) gcar.run (0)"  Create the first object of the Eleccar class "ecar=eleccar ("Tesla" ) Ecar.fill_fuel (60.0) ecar.run (200.0)

Full attributes:

classCar:def __init__(self,name): Self.name=name Self.remain_mile=0defFill_fuel (self,miles): Self.remain_mile=milesdefRun (self,miles):Print(self.name,end=':')        ifself.remain_mile>=Miles:self.remain_mile-=milesPrint("Run%d miles!"%(Miles,))Else:            Print("Fuel out!")classGascar (Car):defFill_fuel (Self,gas): Self.remain_mile=gas*6.0classEleccar (Car):defFill_fuel (self,power): Self.remain_mile=power*3.0Gcar=gascar ("BMW") Gcar.fill_fuel (50.0) gcar.run (0) Ecar=eleccar ("Tesla") Ecar.fill_fuel (60.0) Ecar.run (200.0)

Execute the above code to output the result as follows:

Bmw:run 0 miles! Tesla:fuel out!
Python's underlying overloaded method:
__init__ : This is the constructor of the class, and if you need to implement the class construction method yourself, the overloaded method can
__del__ : Destructor method, which is the method that is called when the object is destroyed, which is called when thedel object is
__repr__: translates into a form for the interpreter to read
__str__ Print object then invokes the __str__ method of the object.
__cmp__ : The comparator method, when sorting the built-in data types such as int and STR, the Python sorted () is sorted by the default comparison function CMP, but if you sort an instance of a group of Student classes, We have to provide our own special method. __cmp__ ()
operator overloading for Python:
classForce :def __init__(self,x,y): self.fx, Self.fy=x, ydefShow (self):Print("force<%s,%s>"%(self.fx, self.fy))defAdd (SELF,FORCE2): x=SELF.FX +force2.fx y=self.fy +Force2.fyreturnForce (x, y)def __str__(self):return "force<%r,%r>"%(self.x, SELF.Y)def __mul__(self, N): x, y=self.x+ N, self.y+NreturnForce (x, y)def __add__(self, Other): X, y=self.x+other.x, self.y+Other.yreturnForce (x, y)def __eq__(self, Other):return(self.x = = other.x) and(Self.y = =other.y)def __repr__(self):return "Force ({0.x!r},{0.y!r})". Format (self) F1=force (0,1) f1.show () F2=force (3,4) F3=F1.add (F2) f3.show ()

The results of the implementation are as follows:

Second, Python exception handling1. Python Standard exceptions
1 Baseexception base class for all exceptions2 Systemexit interpreter Request Exit3Keyboardinterrupt user interrupt execution (usually input ^C)4 Exception base class for general errors5 Stopiteration iterator with no more values6 generatorexit Generator (generator) exception occurred to notify Exit7 StandardError base class for all built-in standard exceptions8 Arithmeticerror base class for all numeric calculation errors9 Floatingpointerror Floating-point calculation errorTen Overflowerror numeric operation exceeds maximum limit One Zerodivisionerror except (or modulo) 0 (all data types) A Assertionerror Assertion statement failed - Attributeerror object does not have this property - Eoferror has no built-in input to reach the EOF tag the EnvironmentError base class for operating system errors -IOError input/output operation failed - OSError Operating system error - windowserror system call failed +Importerror Import Module/object failed - Lookuperror base class for invalid data queries + This index is not in the Indexerror sequence (index) A This key is not in the Keyerror map at memoryerror Memory overflow error (not fatal for Python interpreter) -Nameerror not declared/Initialize object (no attributes) - unboundlocalerror access to uninitialized local variables - referenceerror Weak reference (Weak reference) attempts to access objects that have been garbage collected - RuntimeError General run-time errors - Notimplementederror methods that have not yet been implemented in syntaxerror Python Syntax error - indentationerror Indent Error to Taberror Tab and Space mix + SYSTEMERROR General interpreter system error - TypeError operations that are not valid for types the valueerror Invalid arguments passed in * unicodeerror Unicode-related errors $ unicodedecodeerror Unicode decoding errorPanax Notoginseng unicodeencodeerror Unicode encoding error - unicodetranslateerror Unicode Conversion Error the base class for Warning warnings + deprecationwarning warning about deprecated features A futurewarning warning about the change in the construction of future semantics the overflowwarning old warning about auto-promotion to Long integer + pendingdeprecationwarning warnings about attributes that will be discarded - runtimewarning warning for suspicious runtime behavior (runtime behavior) $ syntaxwarning warning of suspicious syntax $Userwarning warning for user code generation
1 Try:2< statements >#Run another code3 except< name >:4< statements >#if the ' name ' exception is thrown in the try section5 except< name >,< data >:6< statements >#if the ' name ' exception is thrown, get additional data7 Else:8< statements >#If no exception occurs

Third, Python's common knowledge points of the three-party module basically, all third-party modules are registered on the Pypi-the Python Package index and can be installed with Easy_install or PIP as long as the corresponding module name is found.

    • PIL's Imagedraw provides a series of drawing methods that allow us to draw directly. For example, to generate a letter Captcha image:
1 ImportImage, Imagedraw, Imagefont, ImageFilter2 ImportRandom3 4 #Random Letters:5 defRndchar ():6     returnChr (Random.randint (65, 90))7 8 #random color 1:9 defRndcolor ():Ten     return(Random.randint (255), Random.randint (255), Random.randint (64, 255)) One  A #Random color 2: - defRndColor2 (): -     return(Random.randint (127), Random.randint (127), Random.randint (32, 127)) the  - #x: -width = 60 * 4 -Height = 60 +Image = Image.new ('RGB', (width, height), (255, 255, 255)) - #To Create a Font object: +Font = Imagefont.truetype ('Arial.ttf', 36) A #To create a draw object: atDraw =Imagedraw.draw (image) - #fill each pixel: -  forXinchRange (width): -      forYinchRange (height): -Draw.point ((x, y), fill=Rndcolor ()) - #Output Text: in  forTinchRange (4): -Draw.text (* t + ten), Rndchar (), Font=font, fill=RndColor2 ()) to #Blur: +Image =Image.filter (Imagefilter.blur) -Image.Save ('code.jpg','JPEG');

manipulating Images

Iv. Summary of the Pyhone Phase II

through just a few weeks of study, let me have a basic understanding of pythone, let me also know the language, language and language have similar places, Python learning to feel similar to Java, but there are very different, the whole learning process, Let me realize that as long as serious study, there is a harvest, although the course of the teaching process is going to end, but I know that the pace of my study can not stop, I will always learn about this is just to improve their language skills.

Python Phase Summary II

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.