Python basic grammar (b)

                                                                -------------------------------------------- take Python basic grammar (two )  --------------------------------------------

Seven, object-oriented programming

  python support object-oriented programming; classes and objects are the two main aspects of object-oriented programming, class creates a new type of object is an instance of this class.

  Common variable objects can store data belonging to the object, belonging to the object or class variable is called domain ; objects may be used belong to the class of functions, such function is called class methods; fields and methods may be collectively referred to as class Attributes.

  There are two types of field - belonging to the instance, or belong to the class itself; they are called instance variables and class variables.

  Class keyword class to create, classes fields and methods are listed in an indented block.

  Methods of the class must have an extra first argument, but is not assigned to this parameter when you call this particular variable refers to the object itself, as usual it is the name of Self , similar to C # in this.

class Animal:
    pass #empty block

  __init__ method when the method is called an object class is created; c ++ constructor corresponding to the.

  __del__ method calls the method when the object class is destroyed; equivalent destructor in c ++. When using del to delete an object will call __del__ method.

  Python all class members (including the data members) are public; only one exception, data member if you are using a double underscore as a prefix, for the private variables.

Copy the code
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'
Copy the code

  Inheritance: In order to use inheritance, the name of the base class as a tuple follows the class name; python support multiple inheritance. Here is an example of inheritance:

Copy the code
 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'''
10         print "Name: %s, Age: %s, " % (self.name, self.age),
11 
12 class Teacher(SchoolMember):
13     '''Represent a teacher.'''
14     def __init__(self, name, age, salary):
15         SchoolMember.__init__(self, name, age)
16         self.salary = salary
17         print "Initializing a teacher"
18 
19     def tell(self):
20         SchoolMember.tell(self)
21         print "Salary: %d" % self.salary
22 
23 class Student(SchoolMember):
24     '''Represent a student.'''
25     def __init__(self, name, age, marks):
26         SchoolMember.__init__(self, name, age)
27         self.marks = marks
28         print "Initializing a student"
29 
30     def tell(self):
31         SchoolMember.tell(self)
32         print "Marks: %d" % self.marks
33 
34 print SchoolMember.__doc__
35 print Teacher.__doc__
36 print Student.__doc__
37 
38 t = Teacher("Mr. Li", 30, 9000)
39 s = Student("Peter", 25, 90)
40 
41 members = [t, s]
42 
43 for m in members:
44     m.tell()
Copy the code

  Program output is as follows:

Copy the code
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
Copy the code

  

Eight input / output

  Program requires interaction with a user input / output, including the console and files; may be used for the console and Print raw_input, str class may also be used. the raw_input (xxx) xxx input and reads the user's input and returns.

  1. The file input / output

    Class file may be used to open a file, using the read file, write the readline and to properly read and write the file. File reading and writing skills depending on the mode used to open the file, common mode

  There read mode ( "r"), the write mode ( "w"), append mode ( "a"), you need to call the close method to close the file after the file operation.

Copy the code
 1 test = '''\
 2 This is a program about file I/O.
 3 
 4 Author: Peter Zhange
 5 Date: 2011/12/25
 6 '''
 7 
 8 f = file("test.txt", "w") # open for writing, the file will be created if the file doesn't exist
 9 f.write(test) # write text to file
10 f.close() # close the file
11 
12 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 file
17         break
18     print line,
19 
20 f.close()
Copy the code

  

  2. Memory

    python provides a standard module, becoming the pickle, it may be stored using any python objects in a file, can be completely taken out after, this is referred to persistently stored objects; become the cPickle there is another module, and its function pickle exactly the same, except that it is written with c, faster than pickle speed (about 1,000 times faster).

Copy the code
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']
Copy the code

  

Nine, abnormal

  When some abnormal condition occurs in a program, an exception occurs. python can use try ... except processing.

Copy the code
try:
    print 1/0
except ZeroDivisionError, e:
    print e
except:
    print "error or exception occurred."

#integer division or modulo by zero
Copy the code

  

  It lets try ... except on a linked else, when no abnormality is executed else.

  We can define your own exception classes need to inherit Error or Exception.

Copy the code
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 you input an EOF?"
except ShortInputException, ex:
    print "The lenght of input is %d, was expecting at the least %d" % (ex.length, ex.atleast)
else:
    print "no exception"
#The lenght of input is 1, was expecting at the least 3
Copy the code

  try...finally

Copy the code
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..."
Copy the code

  

 

Guess you like

Origin www.cnblogs.com/jianaer/p/11788416.html