Little Turtle Python Study notes

Source: Internet
Author: User

One

IsDigit ()
True:unicode number, byte digit (single byte), full-width digit (double byte), Roman numerals
False: Chinese numerals
Error: None

Isdecimal ()
True:unicode number, full-width digit (double-byte)
False: Roman numerals, Chinese numerals
Error:byte number (single byte)

IsNumeric ()
True:unicode numbers, full-width numerals (double-byte), Roman numerals, Chinese numerals
False: None
Error:byte number (single byte)

Second,and,or

And the expression is evaluated from left to right in python, and if all values are true, the last value is returned, and if there is a false, the first false value is returned.

The or is also left-to-right with a computed expression, returning the first true value.

three , Priority

Power arithmetic > sign > arithmetic operators > comparison operators > logical operators

-3**2=-9 The priority of the 3**-2=0.1111111111 power operation: When combined with a single-mesh operator (typically a minus sign), the priority is lower than the right, and higher than the priority on the left.

Four, hash / dictionary / map / Hash

Dict is a built-in function, you must use parentheses to enclose the content, this is the outermost layer of parentheses, because the DICT function only supports one parameter, so the F I s h c these elements are wrapped in parentheses to simulate a parameter, actually these elements are separated, the parentheses are the middle layer, The inner brackets are just used to separate each element.

Dict.setdefault () If a number is quoted when the key is in use, there is no quotation mark in the display, and if it is a letter or symbol, there is a quotation mark. If the key in the parentheses already exists in the dictionary, the value corresponding to the key is displayed.

Five, embedded functions and closures

Global

Nonlocal

Six, Os

OS. Walk (top) iterates through all subdirectories in the top directory and returns a ternary group (' path ', [path contains directory],[path containing file])

>>> test = Os.walk (R ' D:\Python34\test ')
>>> Test
<generator Object Walk at 0x02365da0>
>>> temp = list (test)
>>> for each in temp:
each


(' D:\\python34\\test ', [' 002 ', ' 0035 ', ' the second file under test '], [' Intorfloat-copy-copy. Py ', ' intorfloat-1.py ', ' intorfloat.py ', ' l og_in-box.py ', ' log_in rename. Py '])
(' d:\\python34\\test\\002 ', [], [' guess.py ', ' flowchart. png ', ' flowchart. Vsd '])
(' d:\\python34\\test\\0035 ', [], [' case01.py '])
(' second file under D:\\python34\\test\\test ', [' Next Level Folder '], [])
(' second file under D:\\python34\\test\\test \ \ Next Level folder ', [], [])

Seven, Locals and Globals

Python two built-in functions--locals and Globals


These two functions primarily provide a way to access local and global variables based on a dictionary.
in understanding these two functions, let's first understandThe concept of namespaces in Python. Python uses a name space called
something to record the trajectory of the variable. namespace is just a dictionary, its key word is the variable name, the value of the dictionary is those who change
value of the volume. In fact, namespaces can be likeA Dictionary of Python access
each function has its own namespace, called the local namespace, which records the variables of the function, including the parameters of the function
and locally defined variables. Each module has its own namespace, called the global namespace, which records the module's change
, including functions, classes, other imported modules, module-level variables, and constants. There is also a built-in namespace, any modulo
block can access it, which holds the built-in functions and exceptions.
when a line of code is to use a variableThe value of x, Python will go to all available namespaces to look for variables, in the following order:
1. Local namespace-refers to the method of the current function or class. If a function defines a local variable X,python will use the
This variable and then stop the search.
2. Global namespace-specifically, the current module. If the module defines a variable called X, a function or a class, Python
This variable will then be used to stop the search.
3. Built-in namespaces-Global for each module. As a final attempt, Python will assume that X is a built-in function or variable.
ifPython cannot find x in these namespaces, it discards the lookup and throws an Nameerror exception, passing
There is no variable named ' x ' such a message.

Eight

use dir (classname) to see what's in the class.
Use dir (instance) to see what's in the instance.
use __dict__ to see what properties are available
See which properties are the same with ID ()
I came to the conclusion through a series of tests:
all of the things in the class "copy" instances include class functions, static functions, class variables, which can actually invoke class variables of the same name through an instance
Instance__class__.value
In addition , self is used for binding, which can be seen by directly printing the function name to see which class object is bound
There are also inheritance, and you can use the above method to look at what is in these parent subclasses: In fact, all the things in the parent class are copied to the subclass, it is the display binding to facilitate the use of the subclass instance call the Parent class method: The child class should be bound to the parent class function
In the final analysis, it is Python's design philosophy is better, can use some methods to clearly see all things, compared to Java can only look at the data to see what kind of things in the class, inheritance, when the creation of the instance when the change occurred.

Nine , some built-in function usages in the Python class

1.Issubclass (Class,classinfo) method that determines whether a class is a subclass of another class or class that is a tuple of one of the classes

>>> class A:
Pass
>>> class B (A):
Pass
>>> Issubclass (B,a)
True
>>> Issubclass (B,object)
True
>>> Issubclass (b,b)
True

2.isinstance (Object,class) to determine if it is a class of instanced objects

>>> class A:
Pass
>>> class B (A):
Pass
>>> a = A ()
>>> B = B ()
>>> isinstance (A,a)
True
>>> Isinstance (A, B)
False
>>> isinstance (b,b)
True
>>> isinstance (B,a)
True

3.hasattr (object,name) tests whether an object has a specified property

4.getattr (Object,name[,default]) returns the value of a member within an object

>>> class C:
def __init__ (self,size):
Self.size = Size

>>> C1 = C (3)

>>> GetAttr (c1, ' size ')
3

>>> getattr (S1, ' size ', ' property does not exist! ‘)
' attribute does not exist! ‘

5.SetAttr (object,name,value) sets the value of a variable within an object

>>> class C:
def __init__ (self,size):
Self.size = Size

>>> C1 = C (3)

>>> setattr (c1, ' Size ', 5)
>>> GetAttr (c1, ' size ')
5

6.delattr (object,name) Delete a variable of an object

>>> class C:
def __init__ (self,size):
Self.size = Size
>>> C1 = C (3)

>>> delattr (c1, ' size ')
>>> GetAttr (c1, ' size ', '%s variable '% not present in ' object%s ' (' C1 ', ' size ')
' Size variable does not exist within object C1

7.Property (Fget=none,fset=none,fdel=none,doc=none) sets properties with attributes, the first parameter is the method name that gets the property of the object, the second parameter is the method name that sets the property of the object, and the third parameter is the method name that removes the object property , you can assign it to an object property, then call the Get object property method defined within the object when it is called on an object, call the method that sets the property of the object when it is assigned, and invoke the method to delete the object property when the Del statement is deleted, for example:
>>> class Case:
def __init__ (self,size):
Self.size = Size
def getsize (self):
Print (' Calling method to get object properties! ‘)
Return self.size
def setSize (Self,value):
Print (' The method that sets object properties is being called! ‘)
Self.size = value
def delsize (self):
Print (' calling method to delete object Properties! ‘)
Del self.size
X = Property (getsize,setsize,delsize)
>>> S1 = case (3)
>>> s1.x
calling methods to get object properties!
3
>>> s1.x = 5
calling methods to set object Properties!
>>> s1.x
calling methods to get object properties!
5
>>> del s1.x
calling methods to delete object Properties!
>>> getattr (S1, ' size ', ' property does not exist! ‘)
‘property does not exist! ‘

Ten, modifier (adorner)

Finally figured out the basic concept of this modifier.
This modifier @ is actually a concept based on closures.
My question inside, said usually func () to rewrite it again, should be said at the time of the definition is this,
Def timeslong ():
def func ():
.....
Then the call is a = Timeslong () a () before calling to Func (). That's probably what it means.

But if you use modifiers
@timeslong
def func ()
The func is directly passed in as a parameter of Timeslong, returning an object and assigning a value to the Func
That is: func () = Timeslong (func) ()

Attached: https://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html

11. global variables and local variables

Reference:https://www.cnblogs.com/z360519549/p/5172020.html

12. Coding

What is Coding ?



in fact, computers only know0 and 1, however, we can display the text through the computer, which is achieved by coding. Encoding is actually an agreed protocol, such as the ASCII encoding convention the uppercase letter A corresponds to the decimal number 65, then when reading a string, see 65, the computer will know that this is the meaning of capital A.

since the computer was invented by the Americans, theASCII encoding is designed with only 1 bytes of storage (in fact only 7 bits, 1 bytes with 8 bits), including uppercase and lowercase letters, numbers, and some symbols. But after computers became ubiquitous in the world, ASCII coding was a bottleneck, since 1 bytes were not enough to accommodate the languages of each country.

Everyone knows that English is only used26 letters can be composed of different words, and the Chinese light characters commonly used there are thousands of, at least 2 bytes to be enough to store, so later China developed a GB2312 code, used to encode Chinese characters.

then Japan developed for its own writingShift_JIS coding, South Korea for their own text developed EUC-KR coding, in the moment, countries have developed their own standards. It is not difficult to imagine that different standards put together, there is inevitably conflict. This is why the original computer is always easy to see garbled phenomenon.

to solve this problem,Unicode encoding was born. The idea of a Unicode organization was initially simple: Create a code that is large enough to add code to all countries and unify standards.

yes, that would solve the problem. But the new problem also arises: if you write text that contains only English and numbers, then useUnicode encoding is a special waste of storage space (ASCII encoding consumes only half of the storage space). So in the spirit of being able to save a little bit, Unicode also creates a variety of implementations.

like the usualUTF-8 encoding is a way of implementing Unicode, which is a variable-length encoding. Simply put, when your text is ASCII-encoded, it is stored in 1 bytes, and when your text is a different Unicode character, it will be converted by an algorithm, with each character stored in bytes. This enables efficient space-saving purposes.

13 , crawler

1.(recommended) since GBK is backwards compatible with GB2312, so you detect is GB2312, then encode/decode directly with GBK

>>> if Chardet.detect (response) [' encoding '] = = ' GB2312 ':

Response.decode (' GBK ')

......

<ul><li># <a href= "thread-64400-1-1.html" title= "Steve Jobs ' most wonderful speech: These three stories have decided my life" target= "_blank" > Steve Jobs ' best speech: These three stories determine one of my </a></li><li># <a href= "thread-50608-1-1.html" title= "42 ways to exercise the brain, You don't want to be smart! "target=" _blank ">42 a way to exercise your brain, you don't want to be smart! </a></li><li># <a href= "thread-23917-1-1.html" title= "Dick Silk finish, Tears (Turn)" target= "_blank" > Cock silk Watch, Tears (Turn)

2. Get: is a pointer to the server requesting data

POST: is a pointer to the specified server to submit the processed data

3.  urllib.parse.urlencode () encode ( ' Utf-8 ' ) : Encode a date url form utf-8 form

4.   modify heads : ①request before generation: put user-agent in the form of a dictionary head urllib.request.request ( url date head ) passed in.

② after theRequest is generated:req=urllib.request.request(url,Date )

Req.add_header (' user-agent ', ' user-agent corresponding value ')

this incoming

5. Reverse Reference ( link https://www.cnblogs.com/-ShiL/archive/2012/04/06/Star201204061009.html)

what the capturing group matches, and what the reverse reference can only match.

6. forward positive assertion, forward negative assertion, back affirmation assertion, and back-negative assertion

Explain:

Reference Links: https://www.crifan.com/detailed_explanation_about_python_regular_express_positive_lookbehind_assertion/

Links: 78505309

7. What do you mean by Urllib.request.Request ()?

Urllib.request.Request () is not a function, but a class that has a variety of properties and a variety of methods to manipulate. After instantiating a class with a URL parameter, you do not need to customize methods and properties, and you can use the methods and properties in the class to easily manipulate the URL

# the URL can be constructed into a Request object first and passed into the urlopen #Request The meaning of existence is to facilitate the passing of some information at the time of the request, while urlopen does not

8. because urlopen () is not supported for advanced features of some HTTP, we can use the Urllib.request.build_opener () method if we want to modify the header. Of course, you can also use Urllib.request.Request () to implement browser simulations. Focus on the former, the latter in the later study will be used.

Little Turtle Python Study notes

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.