Python learning Memorandum-2

Source: Internet
Author: User
Tags export class

1. Preface
The previous memorandum mentioned the basic Python tutorial. Basically, the examples in this article are the content of Shen jieyuan's concise tutorial. These two articles are both Reading Notes and cannot be derived, it is also intended for self-preparation. The translator will forgive me.
Basically, the explanation in this article is your own understanding. If you do not use the explanations in books, you may feel that your explanations may be easier to remember.

The last memo is mainly about process-oriented. In fact, python is an object-oriented Interpretation Language. The Int type and so on are all objects. obviously different from C/C ++, in these two languages, types are defined as atoms and mainly used to allocate memory bytes, there is no such method. Of course, this has been changed in VC. For example, it is easier to process strings than C.

Python and Perl, or Python, are easy to understand and inefficient.

2. Object-oriented Python
2.1. the class creates a new type, and the instance of the class of the object.
2.2. Objects can store data using common object variables. A variable of an object or class is called a field. Objects can also use functions of classes. Such a function is called a class method. Fields and methods can be collectively called class attributes.
2.3. The domain has two types: the object of each instance/class or the class itself. They are called instance variables and class variables respectively. Class is created using the class keyword. Class fields and methods are listed in an indention block.

3, Class

3.1, self Parameter

Class methods have only one special difference from common functions-they must have an additional first parameter name, but you do not assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention.

Self itself does not need to be assigned a value. Python automatically performs this function. If your instance calls a method, for example, assume that you have a class called myclass and an instance named myobject of this class. When you call this object method myobject. Method (arg1, arg2), this will be automatically converted from Python to myclass. Method (myobject, arg1, arg2)
3.2 Create a class
Let's look at the example below:

      #!/usr/bin/python       # Filename: simplestclass.py       class Person:               pass # An empty block       p = Person()       print p

If you remove the indentation before pass, an error will be prompted. to expect an indent, remember that python uses indentation to differentiate statement blocks. People who are used to C should pay attention to it.
The output is the memory address of the instance.

In addition, it should be noted that a pass must be written for an empty statement in Python, rather than being enclosed in brackets in C, because python uses indentation to differentiate statement blocks. So if you don't indent it, the interpreter will not understand it.
3.3. Object Method
The object method is similar to the function, but an extra self variable is added.
Let's look at a method:

      #!/usr/bin/python      # Filename: method.py     class Person:             def sayHi(self):                print 'Hello, how are you?'    p = Person()    p.sayHi()

# This short example can also be written as person (). sayhi ()
Note that the sayhi method does not have any parameters. I personally think the reason why a self method is required for default parameters may be because python is a gate interpreter language that facilitates interpreter interpretation. I just learned this is just a feeling. please correct me if you are not correct.

3.4. Some special methods.
This actually involves some non-unfamiliar concepts.
3.4.1 _ init _ Method
This method is actually a constructor. you understand it, and I didn't mention it in the previous article. Python does not need to be declared in advance for variables. To be honest, I can tell you the following example, but it is a little uncomfortable.

 #!/usr/bin/python            # Filename: class_init.py            class Person:                def __init__(self, name):                       self.name = name           def sayHi(self):           print 'Hello, my name is', self.name           p = Person('Swaroop')           p.sayHi()           # This short example can also be written as Person('Swaroop').sayHi()

The attribute fields here are not declared, and are not of any type. The explicit syntax in strict C ++ is rather bad.

When creating a new instance of a class, the parameter is included in the parentheses following the class name and passed to the _ init _ method.

If you are used to the mandatory Type declarative language such as C ++/Java, you will find that self. Name is not suitable. You just need to regard the self parameter as a required parameter.

The following example explains why the attribute fields of an instance do not need to be declared. For python, the _ init _ method called is suitable for instance creation.

#!/usr/bin/python# Filename: objvar.pyclass Person:    '''Represents a person.'''    population = 0    def __init__(self, name):        '''Initializes the person's data.'''        self.name = name        print '(Initializing %s)' % self.name        # When this person is created, he/she        # adds to the population        Person.population += 1    def __del__(self):        '''I am dying.'''        print '%s says bye.' % self.name        Person.population -= 1        if Person.population == 0:            print 'I am the last one.'        else:            print 'There are still %d people left.' % Person.population    def sayHi(self):        '''Greeting by the person.        Really, that's all it does.'''        print 'Hi, my name is %s.' % self.name    def howMany(self):        '''Prints the current population.'''        if Person.population == 1:            print 'I am the only person here.'        else:            print 'We have %d persons here.' % Person.populationswaroop = Person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam = Person('Abdul Kalam')kalam.sayHi()kalam.howMany()swaroop.sayHi()swaroop.howMany()

We can see that the _ init _ method uses a name to initialize the person instance. In this method, we increase population by 1 because we have added a person. We can also find that the value of self. Name is specified based on each object, which indicates the essence of self. name as the object variable.

Run the preceding script and prompt exception attributeerror: "'nonetype 'object has no attribute 'Population'" in <Bound Method person. _ del _ of <__ main __. person instance at 0xb7746eec> ignored;

The reason is that the global variable is faulty when the object is destroyed.

I wrote another remark to record my mistakes and experiences. Here I will first list the problems I encountered. Remember not to use the _ def _ method.

You can only use the self variable to refer to the variables and methods of the same object. This is called attribute reference.
In this program, we also see that docstring is equally useful for classes and methods. We can use person. _ Doc _ and person. sayhi. _ Doc _ at runtime to separate document strings of the handler class and method.
Like the _ init _ method, there is also a special method _ del __, which is called when the object disappears. The object is no longer used, and the memory occupied by the object will be returned to the system for use. In this method, we simply subtract 1 from person. Population.

When the object is no longer used, the __del _ method runs, but it is difficult to ensure when the method runs.

We run normally once:

In this script, we add:
Print person. _ Doc __
Print person. sayhi. _ Doc __
Let's take a look at the running results:
B2C @ b2c-server :~ $ Python demo. py
(Initializing swaroop)
Hi, my name is swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is swaroop.
We have 2 persons here.
Represents a person.
Greeting by the person.

Really, that's all it does.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.

Have you found anything? We can see that the document string or description text is not displayed at the end, but the script is actually the last two statements. This is because the _ del _ method, the script is executed at the end, and the instance is destroyed, so the method execution prompts. I understand.
Therefore, this _ del _ Is A destructor, similar to the concept.

In this example, the python class members are open by default, and private members are the features added to the language later. They are marked with double underscores. If a Variable _ VaR is a private variable, external calls, including child classes, are invalid. Python uses the new name of this private variable to avoid external calls. This is very simple, so you will be prompted not to find it.

Logical alignment is required for indentation!

3.5, inheritance

One of the core object-oriented concepts is defined for code reuse and logic relevance. There should be no stranger to those with OOP basics.
Child instances can be naturally used as parent types and support multi-inheritance.

     #!/usr/bin/python# Filename: inherit.pyclass SchoolMember:    '''Represents any school member.'''    def __init__(self, name, age):        self.name = name        self.age = age        print '(Initialized SchoolMember: %s)' % self.name    def tell(self):        '''Tell my details.'''        print 'Name:"%s" Age:"%s"' % (self.name, self.age),class Teacher(SchoolMember):    '''Represents a teacher.'''    def __init__(self, name, age, salary):        SchoolMember.__init__(self, name, age)        self.salary = salary        print '(Initialized Teacher: %s)' % self.name    def tell(self):        SchoolMember.tell(self)        print 'Salary: "%d"' % self.salaryclass Student(SchoolMember):    '''Represents a student.'''    def __init__(self, name, age, marks):        SchoolMember.__init__(self, name, age)        self.marks = marks        print '(Initialized Student: %s)' % self.name    def tell(self):        SchoolMember.tell(self)       print 'Marks: "%d"' % self.markst = Teacher('Mrs. Shrividya', 40, 30000)s = Student('Swaroop', 22, 75)print # prints a blank linemembers = [t, s]for member in members:    member.tell() # works for both Teachers and Students

This example shows the basic meaning of inheritance. In addition, subclass constructor must manually construct the constructor of the parent class and cannot be completed automatically. This is a little different from other OOP languages.
Python does not automatically call the constructor of the basic class. You have to call it in person.

4, I/O

4.1, file

You can create a file class object to open a file.

This Io operation is relatively convenient and can directly call file ()

#!/usr/bin/python# Filename: using_file.pypoem = '''\Programming is funWhen the work is doneif you wanna make your work also fun:        use Perl!'''f = file('poem.txt', 'w') # open for 'w'ritingf.write(poem) # write text to filef.close() # close the filef = file('poem.txt')# if no mode is specified, 'r'ead mode is assumed by defaultwhile True:   line = f.readline()   if len(line) == 0: # Zero length indicates EOF       break   print line,   # Notice comma to avoid automatic newline added by Pythonf.close() # close the file 

We create a file-class instance by specifying the files and modes we want to open. The mode can be read ('R'), write ('W'), or append ('A '). In fact, there are many more modes to use. You can use help (File) to learn more about them.
If no mode is specified, the Read mode is used as the default mode.

In a loop, we use the Readline method to read each row of the file. This method returns a complete line that includes the last line break. Therefore, when an empty string is returned, it indicates that the end of the file has reached, so we stop the loop.

There is a small question here: is the true value of the while statement determined based on context? I can change it to F.

Note: because the content read from the file has ended with a line break, we use a comma in the print statement to remove automatic line breaks. Finally, close the file.

4.2 memory

Python provides a standard module called pickle. Using it, You can store any Python object in a file, and then you can retrieve it completely. This is called a persistent storage object.
Another module, cpickle, has the same functions as the pickle module, except that it is written in C, so it is much faster (1000 times faster than pickle ). C is awesome. Haha

#!/usr/bin/python# Filename: pickling.pyimport cPickle as p#import pickle as pshoplistfile = 'shoplist.data'# the name of the file where we will store the objectshoplist = ['apple', 'mango', 'carrot']# Write to the filef = file(shoplistfile, 'w')p.dump(shoplist, f) # dump the object to a filef.close()del shoplist # remove the shoplist# Read back from the storagef = file(shoplistfile)storedlist = p.load(f)print storedlist

First, note that we use the import... as syntax. This is a convenient method so that we can use shorter module names. In this example, it also enables us to switch to another module (cpickle or pickle) by simply changing one line )! In the rest of the program, we simply call this module p.

To store an object in a file, first open a file object in write mode, then call the dump function of the storage module to store the object to the opened file. This process is called storage.

Next, we use the load function of the pickle module to return the object. This process is called storage fetch.
This is applicable to I/O operations.

5. Exception Handling
It should be said that there is content for exception handling in the advanced language.
The interpreter will tell us that there is an error and sometimes it is unfriendly to users. Therefore, it is a bit similar to catch... throw, where try... throt.

#!/usr/bin/python# Filename: try_except.pyimport systry:    s = raw_input('Enter something --> ')except EOFError:    print '\nWhy did you do an EOF on me?'    sys.exit() # exit the programexcept:    print '\nSome error/exception occurred.'    # here, we are not exiting the programprint 'Done'

After the program runs, press Ctrl + C or Ctrl + D to check the result ..

5.2. A custom exception occurs.
You can customize exceptions to display them.
You can use the raise statement to raise an exception. You must also specify the error/Exception name and the exception object triggered with the exception. The errors or exceptions you can cause should be a direct or indirect export class of the error or exception class.
The defined exception class is a subclass of the exception class.

Here, we have created our own exception types. In fact, we can use any predefined exceptions/errors. The new exception type is the shortinputexception class. It has two fields-length is the length of the given input, and atleast is the minimum length expected by the program.

In the limit t clause, we provide error classes and variables used to indicate error/exception objects. This is similar to the concept of form parameters and real parameters in function calls. In this special limit t clause, we use the length and atleast of the exception object.

#!/usr/bin/python# Filename: raising.pyclass ShortInputException(Exception):    '''A user-defined exception class.'''    def __init__(self, length, atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = raw_input('Enter something --> ')    if len(s) < 3:        raise ShortInputException(len(s), 3)    # Other work can continue as usual hereexcept EOFError:    print '\nWhy did you do an EOF on me?'except ShortInputException, x:    print 'ShortInputException: The input was of length %d, \          was expecting at least %d' % (x.length, x.atleast)else:    print 'No exception was raised.'

Here, we have created our own exception types. In fact, we can use any predefined exceptions/errors. The new exception type is the shortinputexception class. It has two fields-length is the length of the given input, and atleast is the minimum length expected by the program.

In the limit t clause, we provide error classes and variables used to indicate error/exception objects. This is similar to the concept of form parameters and real parameters in function calls. In this special limit t clause, we use the length and atleast fields of the exception object to print an appropriate message for the user.

5.3, try... finally
It can be seen that finally is an action that must be completed whether an exception occurs or not.

 #!/usr/bin/python# Filename: finally.pyimport timetry:    f = file('poem.txt')    while True: # our usual file-reading idiom        line = f.readline()        if len(line) == 0:            break        time.sleep(2)        print line,finally:    f.close()    print 'Cleaning up...closed the file'

After sleeping for 2 seconds, I deliberately extended the time so that you could press Ctrl + C. After pressing it, you also found that the file was closed.

6. Python standard library
6.1, SYS module
As the name implies, the system library.

 #!/usr/bin/python# Filename: cat.pyimport sysdef readfile(filename):    '''Print a file to the standard output.'''    f = file(filename)    while True:        line = f.readline()        if len(line) == 0:            break        print line, # notice comma    f.close()# Script starts from hereif len(sys.argv) < 2:    print 'No action specified.'    sys.exit()if sys.argv[1].startswith('--'):    option = sys.argv[1][2:]    # fetch sys.argv[1] but without the first two characters    if option == 'version':        print 'Version 1.2'    elif option == 'help':        print '''\This program prints files to the standard output.Any number of files can be specified.Options include:  --version : Prints the version number  --help    : Display this help'''    else:        print 'Unknown option.'    sys.exit()else:    for filename in sys.argv[1:]:        readfile(filename)

Here, argv automatically considers the script file name as argv [0] and starts counting from 0. It is the same as the C language. If argv [1] [2:] appears, it is the second parameter. The user's angle is that the first parameter discards the first two characters and truncates the remaining characters.
As for argv [1:], it should be the first parameter from the user's perspective to the end of the parameter list.
The readfile () function outputs the file content. First, it determines the number of parameters. If there are fewer than two parameters, there is obviously no input file name, and a prompt is displayed. If the parameter starts with --, the first two characters are discarded, capture the remaining characters and output the prompts through process matching. Finally, output the files in the parameter list one by one.

There are three modules that are commonly used to write down: SYS. stdin, SYS. stdout, and SYS. stderr correspond to the standard input, standard output, and standard error stream of your program respectively.

6.2, OS Module
This module contains common operating system functions. This module is especially important if you want your program to be unrelated to the platform. That is, it allows a program to run in Linux and Windows without any changes or any problems. In one example, OS. SEP can replace the path delimiter specified by the operating system.
This is very important to me. After all, people who use Linux desktops are very rare.
There are many useful methods in the OS module. You can check the documentation at ordinary times.

The OS. Name string indicates the platform. OS. getcwd () function you are using to obtain the current working directory. The OS. linesep string specifies the row Terminator used by the current platform. The OS. Path. isfile () and OS. Path. isdir () functions verify whether the given path is a file or a directory. Similarly, the OS. Path. Existe () function is used to check whether the GIVEN PATH actually exists.

Basically, the basic things of Python are all here. Of course, it's a little bit of a piece of cake. In the future, I will keep adding content and learning to be forgotten.

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.