Python Learning notes (ii)

Source: Internet
Author: User

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:
#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 has 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:

1Class Schoolmember:
2‘‘‘Represent any school member.‘‘‘
3Def__init__ (self, Name, age):
4 Self.name = Name
5 Self.age = Age
6Print"Initializing a school member."
7
8def tell (self):
9‘‘‘Tell my details‘‘‘
10Print"Name:%s, age:%s,"% (Self.name, self.age),
11
12Class Teacher (Schoolmember):
13‘‘‘Represent a teacher.‘‘‘
14Def__init__ (self, name, age, salary):
Schoolmember.__init__ (self, name, age)
Self.salary = Salary
17Print"Initializing a teacher"
18
19def tell (self):
Schoolmember.tell (self)
21stPrint"Salary:%d"% self.salary
22
23Class Student (Schoolmember):
24‘‘‘represent a student.‘‘‘
25Def__init__ (self, name, age, marks):
Schoolmember.__init__ (self, name, age)
Self.marks = Marks
28Print"Initializing a student"
29
30def tell (self):
Schoolmember.tell (self)
32Print"Marks:%d"% Self.marks
33
34Print Schoolmember.__doc__
35print Teacher. __doc__
36 print Student. __doc__
38 t = Teacher ( " 39 s = Student ( " peter 40
41 members = [T, s]
42
43 for m in Members:

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 =‘‘‘\
2This was a program about file I/O.
3
4Author:peter Zhange
5Date:2011/12/25
6‘‘‘
7
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
11
f = File ("test.txt# If no mode is specified, the default mode is readonly.
13
14 while True:
15 line = F.readline ()
16 if len (line) = = 0: # Zero length indicates the EOF of the FIL E
17 break
Span style= "color: #008080;" >18 print line,
19
20 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", Span style= "color: #800000;" > "john "king "]

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

del namelist

F = file (datafile)
Storednamelist = Cpickle.load (f)

Span style= "color: #0000ff;" >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
"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 have to input an EOF? "
except Shortinputexception, ex:
print " "% (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 ()
"Cleaning up ... "

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

Python Learning notes (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.