Python basic Syntax (iii)

Source: Internet
Author: User
Tags integer division

Python basic Syntax (iii)

--------------------------------------------the basic syntax of Python (ii)--------------------------------------------

Vii. Object-Oriented programming

Python supports object-oriented programming, classes and objects are the two main aspects of object-oriented programming, and classes create a new type that is an instance of this class.

objects can store data using ordinary variables belonging to objects, which are referred to as domains , and objects can also use functions belonging to classes, which are called methods of classes, and fields and methods can be called properties of classes.

There are two types of domains--instances or classes themselves--which are referred to as instance variables and class variables, respectively.

Class is created using the keyword class, and the fields and methods of the class are listed in an indented block.

The method of a class must have an additional first parameter, but not assign a value to the parameter at the time of invocation, this special variable refers to the object itself, by convention its name is self, similar to this in C #.

Class Animal:
Pass #empty Block

The __init__ method calls the method when an object of the class is created, which is equivalent to a constructor in C + +.

The __del__ method calls the method when the object of the class is destroyed, equivalent to a destructor in C + +. The __del__ method is also called when you use Del to delete an object.

All class members (including data members) in Python are public, and only one exception is private if the data member used is prefixed with a double underscore.

Class Person:
Count = 0
def __init__ (self, Name, age):
Person.count + = 1
Self.name = Name
Self.__age = Age

p = person ("Peter", 25)
P1 = Person ("John", 20)

Print Person.count #2
Print P.name #peter
Print p.__age #AttributeError: person instance have no attribute ' __age '

Inheritance: In order to use inheritance, the name of the base class follows the class name as a tuple, and Python supports multiple inheritance. Here is an example of inheritance:

1 class Schoolmember:
2 "represent any school member."
3 def __init__ (self, Name, age):
4 Self.name = Name
5 Self.age = Age
6 print "Initializing a school member."
7
8 def Tell (self):
9 "Tell my Details"
Print "Name:%s, Age:%s,"% (Self.name, self.age),
11
Class Teacher (Schoolmember):
"' represent a teacher."
def __init__ (self, name, age, salary):
Schoolmember.__init__ (self, name, age)
Self.salary = Salary
Print "Initializing a teacher"
18
def tell (self):
Schoolmember.tell (self)
Print "Salary:%d"% self.salary
22
Class Student (Schoolmember):
"Represent a student."
def __init__ (self, name, age, marks):
Schoolmember.__init__ (self, name, age)
Self.marks = Marks
Print "Initializing a student"
29
def tell (self):
Schoolmember.tell (self)
Print "Marks:%d"% self.marks
33
Print schoolmember.__doc__
Print teacher.__doc__
Print student.__doc__
37
$ t = Teacher ("Mr. Li", 30, 9000)
s = Student ("Peter", 25, 90)
40
Members = [T, S]
42
A for M in Members:
M.tell ()

The program output is as follows:

Represent any school member.
Represent a teacher.
represent a student.
Initializing a school member.
Initializing a teacher
Initializing a school member.
Initializing a student
NAME:MR Li, age:30, salary:9000
Name:peter, age:25, marks:90

Eight, input/output

The interaction between the program and the user requires input/output, primarily the console and files, and the Str class can be used with raw_input and print for the console. Raw_input (XXX) Enter XXX and then read the user's input and return.

1. File input/Output

You can open a file using the file class, using file read, ReadLine, and write to read and write files appropriately. The ability to read and write files depends on the mode used when opening the file, common mode

Have read mode ("R"), Write Mode ("W"), Append Mode ("a"), the file operation needs to call the Close method to close the file.

1 Test = "\
2 This was a program about file I/O.

4 Author:peter Zhange
5 DATE:2011/12/25
6 ""

8 F = File ("Test.txt", "W") # Open for writing, the file would be created if the file doesn ' t exist
9 F.write (test) # Write text to file
Ten F.close () # Close the file

f = File ("test.txt") # If no mode is specified and the default mode is readonly.

While True:
Line = F.readline ()
If Len (line) = = 0: # Zero length indicates the EOF of the file
Break
Print Line,

F.close ()

2. Memory

Python provides a standard module, which becomes pickle, which can store any Python object in a file, which can then be completely removed, which is called persistent storage object, and another module becomes cpickle, which functions exactly like pickle. But it is written in C, faster than pickle (about 1000 times times faster).

Import Cpickle

datafile = "Data.data"

NameList = ["Peter", "John", "King"]

f = File (DataFile, "w")
Cpickle.dump (NameList, F)
F.close ()

Del NameList

f = File (datafile)
Storednamelist = Cpickle.load (f)

Print Storednamelist
#[' Peter ', ' John ', ' King '

Nine, abnormal

An exception occurs when certain abnormal conditions occur in the program. Python can be processed using the try ... except.

Try
Print 1/0
Except Zerodivisionerror, E:
Print E
Except
Print "error or exception occurred."

#integer division or modulo by zero

You can have try ... except associated with an else, or else when there is no exception.

We can define our own exception classes and need to inherit the error or exception.

Class Shortinputexception (Exception):
"A user-defined Exception class"
def __init__ (self, length, atleast):
Exception.__init__ (self)
Self.length = length
Self.atleast = atleast

Try
s = Raw_input ("Enter Someting-->")
If Len (s) < 3:
Raise Shortinputexception (Len (s), 3)
Except Eoferror:
Print "Why do you input an EOF?"
Except Shortinputexception, ex:
Print "The lenght of input is%d, were expecting at the least%d"% (Ex.length, ex.atleast)
Else
Print "no exception"
#The lenght of input is 1, were expecting at the least 3

Try...finally

Try
f = File ("Test.txt")
While True:
line = F.readline ()
If Len (line) = = 0:
Break
Time.sleep (2)
Print line,
Finally
F.close ()
Print "Cleaning up ..."

----------------------------------------------See continued Python basic Syntax (iv)----------------------------------------------

Python basic Syntax (iii)

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.