Python learning Memorandum

Source: Internet
Author: User
Tags export class natural string processing text

Source: http://blog.csdn.net/nilxin/article/details/1613574

Special methods in the class

Generally, special methods are used to imitate a behavior. For example, if you want to use index operations such as X [Key] for your class (just like the list and metadata), you only need to implement _ getitem __() method. Think about it. Python does this for the List class!

The following table lists some useful special methods. If you want to know all the special methods, you can find a huge list in the python reference manual.

Description
---------------------------------------------------------
_ Init _ (self,...) is called before the newly created object is returned for use.
_ Del _ (Self) is called just before the object is deleted.
_ STR _ (Self) is called when we use the print statement for the object or STR.
_ LT _ (self, other) is called when the less than operator (<) is used. Similarly, all operators (+,>, and so on) have special methods.
_ Getitem _ (self, key) is called when the X [Key] index operator is used.
_ Len _ (Self) is called when the built-in Len () function is used for the sequence object.
_ Repr _ (s) repr () and '...' Conversions
_ CMP _ (s, O) compares s to O and returns <0, 0, or> 0.
Implements>, <, = etc...
_ Hash _ (s) compute a 32 bit hash code; Hash () and dictionary Ops
_ Nonzero _ (s) returns 0 or 1 for truth value testing
_ Getattr _ (s, name) called when ATTR lookup doesn't find <Name>
_ Setattr _ (s, name, Val) called when setting an ATTR
(Inside, don't use "self. Name = value"
Use "self. _ dict _ [name] = Val ")
_ Delattr _ (s, name) called to delete ATTR <Name>
_ Call _ (self, * ARGs) called when an instance is called as function.

Exec and eval statements

Exec statements are used to execute Python statements stored in strings or files. For example, we can generate a string containing Python code at runtime, and then execute these statements using exec statements.

The following is a simple example.

>>> Exec 'print "Hello World "'
Hello World

The eval statement is used to calculate the valid Python expression stored in the string. The following is a simple example.

>>> Eval ('2*3 ')
6

Assert statement

The assert statement is used to declare that a condition is true. For example, if you are very sure that a list you are using has at least one element, and you want to test this and cause an error when it is not true, the assert statement is an ideal statement applied in this case. When the assert statement fails, an assertionerror is thrown.

>>> Mylist = ['item']
>>> Assert Len (mylist)> = 1
>>> Mylist. Pop ()
'Item'
>>> Assert Len (mylist)> = 1
Traceback (most recent call last ):
File "<stdin>", line 1, in?
Assertionerror repr Function

The repr function is used to obtain the standard string representation of an object. Backquotes (also called Conversion characters) can accomplish the same function. Note: In most cases, Eval (Repr (object) = object.

>>> I = []
>>> I. append ('item ')
>>> 'I'
"['Item']"
>>> Repr (I)
"['Item']"

Basically, the Repr function and backquotes are used to obtain the printable representation of an object. You can define the _ repr _ method of the class to control the content returned when your object is called by the Repr function.

Class and instance variable

There are two types of domains: class variables and object variables. They are differentiated based on whether the class or object owns the variable.

Class variables are shared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.

The object variables are owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. This is easy to understand through an example.

#! /Usr/bin/Python
# Filename: objvar. py

Class 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. Population

Swaroop = person ('swaroop ')
Swaroop. sayhi ()
Swaroop. howoop ()

Kalam = person ('Abdul kalam ')
Kalam. sayhi ()
Kalam. Howmany ()

Swaroop. sayhi ()
Swaroop. howoop () Output

___ Fckpd ___ 5 nbsp; Python objvar. 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.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.

This is a long example, but it helps to describe the nature of the variables of classes and objects. Here, population belongs to the person class, so it is a class variable. The name variable belongs to the object (which uses self to assign values). Therefore, it is the variable of the object.

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.

Remember, 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. If you want to specify how it runs, you have to use the del statement, as we used in previous examples.

Comments to C ++/Java/C # programmers

All class members (including data members) in Python are public and all methods are valid.

Only one exception: if you use a data member name with a double-underline prefix such as _ privatevar, the python name management system will effectively use it as a private variable.

In this way, there is a convention that if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ).

Similarly, the _ del _ method is similar to the Destructor method.

Inheritance

One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.

Suppose you want to write a program to record the teachers and students in the school. They have common attributes, such as names, ages, and addresses. They also have proprietary attributes, such as teachers' salaries, courses and holidays, students' scores and tuition fees.

You can create two independent classes for the instructors and students to process them. However, if you want to add a new common attribute, this means that this attribute must be added to both independent classes. This will soon become impractical.

A better way is to create a common class called schoolmember and let the classes of teachers and students inherit this common class. That is, they are all subtypes of this type (class), and then we add proprietary attributes for these subtypes.

This method has many advantages. If we add/change any feature in schoolmember, it will be automatically reflected in the Child type. For example, if you want to add a new ID field for both teachers and students, simply add it to the schoolmember class. However, the changes made in a subtype do not affect other subtypes. Another advantage is that you can use both teachers and students as schoolmember objects, which is particularly useful in some occasions, such as counting the number of school members. A child type can be replaced with the parent type in any scenario where the parent type is required, that is, the object can be considered as an instance of the parent class. This phenomenon is called polymorphism.

In addition, we will find that when reusing the code of the parent class, we do not need to repeat it in different classes. If we use an independent class, we have to do so.

In the preceding scenario, the schoolmember class is called a basic class or a superclass. The teacher and student classes are called export classes or subclasses.

Now we will learn an example program.

Use inheritance

#! /Usr/bin/Python

# Filename: Inherit. py


Class 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. Salary


Class 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. Marks


T = teacher ('Mrs. shrividya', 40,300 00)

S = student ('swaroop ', 22, 75)


Print # prints a blank line


Members = [t, s]

For member in members:

Member. Tell () # works for both teachers and students output


$ Python inherit. py

(Initialized schoolmember: Mrs. shrividya)

(Initialized Teacher: Mrs. shrividya)

(Initialized schoolmember: swaroop)

(Initialized Student: swaroop)


Name: "mrs. shrividya" Age: "40" Salary: "30000"

Name: "swaroop" Age: "22" marks: "75"

To use inheritance, we use the basic class name as a tuples after the class name when defining the class. Then, we noticed that the _ init _ method of the basic class is called using the self variable, so that we can initialize the basic class part of the object. This is important at 01:10 -- Python does not automatically call the constructor of the basic class. You have to call it in person.

We also observe that we add the class name prefix before the method call, and then pass the self variable and other parameters to it.

Note that when we use the tell method of the schoolmember class, we only use the instance of teacher and student as the instance of schoolmember.

In addition, in this example, we call the tell method of the child type, instead of the tell method of the schoolmember class. It can be understood that python always finds the corresponding type of method first, which is the case in this example. If it cannot find the corresponding method in the export class, it will start to search for it one by one in the basic class. The basic class is specified in the tuples when the class is defined.

Annotation of a term-if more than one class is listed in the inheritance tuples, it is called multi-inheritance.

String

A string is a string of characters. A string is basically a group of words.

I can almost ensure that you use strings in every Python program, so pay special attention to the following content. The following describes how to use strings in Python.

* Use single quotes (')

You can use single quotes to indicate strings, just like 'quote me on this. All spaces, that is, spaces and tabs are retained as they are.

* Use double quotation marks (")

The strings in double quotes are exactly the same as those in single quotes. For example, "What's your name? ".

* Use three quotation marks (''' or """)

You can use three quotation marks to indicate a multi-line string. You can use single quotes and double quotes freely in three quotes. For example:

'''This is a multi-line string. This is the first line.

This is the second line.

"What's your name ?, "I asked.

He said "Bond, James Bond ."

'''

* Escape Character

Suppose you want to include a single quotation mark (') in a string, how do you indicate this string? For example, the string is what's your name ?. You certainly won't use what's your name? 'To indicate it, Because python will not understand where the string starts and ends. Therefore, you must specify single quotes instead of the end of the string. You can use escape characters to complete this task. You use/'to indicate single quotes -- pay attention to this backslash. Now you can represent the string as 'What/'s your name? '.

The other method to indicate this special string is "What's your name? ", That is, double quotation marks. Similarly, to use double quotation marks in a double quotation mark string, you can also use escape characters. In addition, you can use the Escape Character // to indicate the backslash itself.

One thing worth noting is that in a string, a separate backslash at the end of the line indicates that the string continues in the next line, rather than starting a new row. For example:

"This is the first sentence ./

This is the second sentence ."

It is equivalent to "This is the first sentence. This is the second sentence ."

* Natural string

If you want to indicate certain strings that do not require special processing such as escape characters, you need to specify a natural string. A natural string is specified by adding the prefix R or R to the string. For example, R "newlines are indicated by/N ".

* Unicode string

Unicode is a standard method for writing international text. If you want to write text in your native language, such as Hindi or Arabic, you need an editor that supports Unicode. Similarly, Python allows you to process Unicode text-you only need to add the prefix U or u before the string. For example, U "this is a unicode string .".

Remember to use Unicode strings when processing text files, especially when you know that the file contains text written in a non-English language.

* The string is unchangeable.

This means that once you create a string, you cannot change it any more. Although it looks like a bad thing, it is actually not. We will see in the subsequent program why we say it is not a disadvantage.

* Literally connected strings

If you put two strings adjacent to each other literally, they will be automatically connected by python. For example, 'What/s' your name? 'Will be automatically converted to "What's your name? ".

Comments to C/C ++ programmers

There is no special char data type in Python. There is no need for this type, and I believe you will not worry about it.

Comments to Perl/PHP programmers

Remember, single quotes and double quotation marks are exactly the same-they are not in any way different.

Comments for regular expression users

Be sure to use natural strings to process regular expressions. Otherwise, a lot of backslash is required. For example, the back reference can be written as '// 1' or R'/1 '.

Private variable

Python partially supports private class members. Any identifier in the form of _ spam (with at least two leading underlines and at most one ending underline) is replaced with _ classname _ spam, classname is the result of removing the leading underline from the class name. This obfuscation can be used to define private instances, variables, methods, and global variables regardless of the identifier's syntax location, or even save instances of other classes that are private to this class. If the name to be disturbed exceeds 255 characters, it may be truncated. Do not stir up when the class name is only underlined.

The purpose of name obfuscation is to give a class a simple way to define "private" instance variables and methods, without worrying that other classes will define variables of the same name, it is not afraid that code outside the class will mess up the instance variables. Note that obfuscation rules are mainly used to avoid accidental errors. If you want to do so, you can still access or modify private variables. This is even useful. For example, private variables are used in debugging programs, which is also one reason why this vulnerability is not blocked. (Small error: the private variables of the base class can be used if the export class and the base class have the same name ).

Note that the Code passed to exec, Eval () or evalfile () does not consider the class names that call their classes as the current class, which is similar to the global statement, the role of global is limited to Code Compiled in bytes. The same restrictions apply to getattr (), setattr (), delattr (), and direct access to _ dict.

The classes in the following example implement their own _ getattr _ and _ setattr _ methods to save all attributes in a private variable, this is feasible in the new and old versions of Python:

Class virtualattributes:
_ Vdict = none
_ Vdict_name = locals (). Keys () [0]

Def _ init _ (Self ):
Self. _ dict _ [self. _ vdict_name] = {}

Def _ getattr _ (self, name ):
Return self. _ vdict [name]

Def _ setattr _ (self, name, value ):
Self. _ vdict [name] = Value

References:

Http://www.e7blog.com/blog/user1/python/

Http://www.czug.org/docs/python/TutorialCN/X_e7_ac_ac_e4_b9_9d_e7_ AB _a0_e7_b1_bb/

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.