Python Knowledge Grooming

Source: Internet
Author: User

This is a personal study note, non-tutorial, the content will be a bit confusing

Minimalist Tutorials Data Type

We can use the type() function class to get the type of the object, the built-in data types in Python3 include: None,int,float,complex,str,list,dict,tuple,set,frozenset,range etc., there are types in Python2, there are long no built-in array types in Python.

dict,list,setThese are mutable types (user-defined types are also mutable), which can change the value of a type object, and numeric and string types are immutable.

    • Str
      As with JS, a string in Python can be enclosed in single quotation marks or double quotes

    • Numbers
      The value types in Python3 are: int and float two kinds

    • List
      Literal means: [1,1.0,false, ' list ']
      List derivation, an easy way to create a list:

    • Tuple
      Literal representation: (1,1.0,false, ' tuple ')

    • Range

list, tuple, range all belong to sequence type (Sequence Types)

    • Dict

    • Set/frozenset
      A collection is a dataset that does not contain duplicate elements, Frozenset is immutable, the set is mutable, and you can use literals to build a collection that {1,2,2,4,5} outputs{1,2,4,5}

Type Conversions

Type conversions in Python require only the relevant function to be called

function
# function definition Template def func_name ([Self,][args]):    passdef Say_hello ():    print (' Hello python! ' # python3.5, you can add a type description when defining a function # Here's just a description document instead of a mandatory type constraint Def type_instruction (num:int)-int:    return num 

Define multiple return value functions

# Multiple return value function, return a tuple object Def multi_returns ():    return 0,1

built-in functions

There are many built-in functions in Python:

    • Dir
      We can use dir() functions to see which members the object contains:

    • Map

    • Filter

    • Reduce is not a built-in function, but it is also useful

Lambda

Use keywords in python to lambda create lambda expressions:

*args and **kvargs

*argsAnd **kvargs both are used in functions to receive multiple parameters, here args and kvargs only by the conventional notation, can be replaced by other names, but the * and ** is necessary.
*args**kvargsthe difference is that it is *args used to accept common parameters, which are **kvargs used to accept key-value pairs.

Ternary operators

Object Oriented

All objects in Python (this sentence is not so easy to understand), including functions (functions in C#,java cannot exist independently). Post a previously written article: classes, objects, inheritance in Python

Python passes objects by reference, creating new objects when they are modified for immutable objects, and for mutable objects, all modifications are reflected on the original object.

The Magic method is an important part of the Python object model.

A property can be dynamically added to an object/type, and if a property is added to the type, it is also visible on the resulting instance:

Exceptions and Errors

The relationship between exception and error classes in Python is as follows:


Custom exceptions can only be inherited Exception or a variety of Error classes

Exception Handling
Try:    raise IOError (' throw exception with raise statement ') except IOError as err:    print(err) Else:    print (' Execute ' If no exception occurs ') finally: Pass      

To capture multiple exception types:

Try:    raise IOError () except (ioerror,typeerror):    pass  

With statement

with...as...Statements are equivalent to try...finally... , similar to statements in C # using

Naming Conventions

Module_name, Package_name, ClassName, Method_name, Exceptionname, Function_name, Global_var_name, Instance_var_name, Function_parameter_name, Local_var_name.

names that should be avoided
    1. Single-character names, in addition to counters and iterators.
    2. Hyphen (-) in Package/module name
    3. A name that begins and ends with a double underscore (python reserved, for example, init)
Naming Conventions
    1. The so-called "internal (Internal)" means that only modules are available within the module, or that they are protected or private within the class.
    2. Starting with a single underscore (_) indicates that a module variable or function is protected (not included when using import * from).
    3. An instance variable or method that begins with a double underscore (__) represents a private in-class.
    4. Place related classes and top-level functions in the same module. Unlike Java, there is no need to restrict a module to a class.
    5. Words that begin with a capital letter for the class name (such as capwords, Pascal style), but the module name should be underlined in lowercase (such as lower_with_under.py). Although there are already many existing modules that use a name similar to capwords.py, it is now discouraged because if the module name happens to coincide with the class name, it can be confusing.
Python's father Guido recommended specification Public
Type Internal
Modules Lower_with_under _lower_with_under
Packages Lower_with_under
Classes Capwords _capwords
Exceptions Capwords
Functions Lower_with_under () _lower_with_under ()
Global/class Constants Caps_with_under _caps_with_under
Global/class Variables Lower_with_under _lower_with_under
Instance Variables Lower_with_under _lower_with_under (Protected) or __lower_with_under (private)
Method Names Lower_with_under () _lower_with_under () (protected) or __lower_with_under (private)
Function/method Parameters Lower_with_under
Local Variables Lower_with_under
Packages and Modules
    • Module
      A file that contains a Python statement or definition is a module with the name of the module. In a module, the module name is __name__ the value of the global variable.

    • Package
      __init__.pythe folder that contains the files is treated as a package, which is used by the management module to prevent module naming conflicts. such as: A.C and B.C , respectively, the C module in a package and the C module in the B package.

    • Import module:
      import a, import a as alias , from a import * ,from a import b,c
      The Python interpreter first looks for the imported module from the built-in module and then sys.path looks for the module from the module search path specified in

Test

Write a file operation class with the file name file_operator.py :

# coding=utf-8import codecsclass fileoperator:    def save_file (self, file_path, content, encoding= "Utf-8 "):        with Codecs.open (File_path," W ", Encoding) as F:            f.write (content)   

Write the test case with the file name test_file_operator.py :

# coding=utf-8import unittestclass testfileoperator (unittest. TestCase):    def test_save_file (self):        content = "file content \ r \ n Text contents"        opt = file. Fileoperator ()        opt.save_file ("1.txt", content) if __name__ = = "__main__": Unittest.main ()  

Tools Recommended
    • IPython
    • VS Code
    • Pycharm
Summary

The above is a summary of their recent study of Python, the main focus of the full text in the Python language itself. After mastering the above, you can write scripts in Python, supplemented by other third-party packages or frameworks to do more and more complex things. For example, reptiles, data analysis, backend development and now more hot AI (in fact, I do not recommend chasing hot spots).

Python is interesting after a period of time.

Finally, attach a personal summary of the language learning routines:

Recommended Reading

Life is short, why should I use Python?
Python style specification
Python language Specification
[Python] Memory management
Python Advanced
Python Getting Started Guide
Python 3.7.0 Documentation

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.