Concise Python Tutorial Notes

Source: Internet
Author: User

Concise Python Tutorial Notes

Original: http://python.swaroopch.com/
Chinese version: https://bop.mol.uno/

  • There are int, float no long, double. There is no char,string to change.
  • Help function
  • If you have a very long line of code, you can split it into multiple physical rows by using a backslash. This is referred to as an explicit row connection (Explicit line joining) 5:

    =‘This is a string. \This continues the string.‘print(s)
    =\5
    In some cases, there is an implicit hypothesis that allows you to not use backslashes. This is the case where the logical line begins with parentheses, which can be square brackets or curly braces, but not the closing parenthesis. This is known as an implicit row connection (implicit line joining).
  • When we declare an asterisk parameter such as *param, all positional parameters (positional Arguments) starting from here until the end are collected and aggregated into a tuple (tuple) called "Param".
    Similarly, when we declare a double-star parameter such as **param, all the keyword arguments starting from here until the end are collected and aggregated into a dictionary called param (Dictionary).

    def  Total (A=  5 , *  numbers, **  Phonebook): print  ( Span class= "st" > ' a ' , a)  #遍历元组中的所有项目  for  single_item in  numbers: print  ( ' Single_item ' , Single_item)  #遍历字典中的所有项目 for  first_part, Second_part in  Phonebook.items (): print  (first_part,second_part) print  (Total ( Span class= "DV" >10 , 1 , 2 , 3 , jack< Span class= "OP" >= 1123 , John =  2231 , Inge =  1560 )) 
  • If the return statement does not match any of the values, it represents a return of none. None is a special type in Python and represents nothingness. Each function implies a return of none at the end, unless you write your own return statement.
  • The pass statement in Python is used to indicate a block of statements with no content.
  • The string in the logical line of the first line of the function is the document string (docstring) of the function, obtained from the function's __doc__ properties, and the Help function is the value that is taken. A string convention (not a must) is a string of multiline strings where the first line begins with a capital letter and ends with a period. The second behavior is a blank line, followed by a third line beginning with any detailed explanation.
  • When the module is imported for the first time, the code it contains will be executed.
  • A package is a folder that contains a module with a special __init__.py file, which indicates to Python that the folder is special because it contains a Python module.
  • There are four built-in data structures in Python-lists, tuples (tuples), dictionaries (Dictionary), and collections (set).
  • The list is mutable (Mutable) and the string is immutable (immutable).
  • Tuple (tuple) is used to save multiple objects together. You can approximate them as lists, but tuples cannot provide a wide range of features that list classes can provide to you. A large feature of tuples is similar to strings, which are immutable, meaning that you cannot edit or change tuples.
  • An empty tuple is composed of a pair of parentheses, like Myempty = (). However, a tuple that has only one project is not as simple as this. You must specify it with a comma after the first (and only) item, so that Python can identify whether the expression is a tuple or just an object surrounded by parentheses.
  • The key value of a dictionary can only use immutable objects, such as strings.
  • Lists, tuples, and strings can be thought of as a representation of a sequence (Sequence). The main function of the sequence is the qualification Test (membership test) (i.e. in and not-in expressions) and index operations (indexing Operations), which allow us to get directly to a specific item in the sequence.
  • If you want to create a copy of a complex object, such as a sequence, rather than an integer (object), you must use the slice operation to make a copy. If you simply assign one variable name to another, they will all reference the same object.
  • Designing our programs around functions, that is, blocks of code that can handle data, is called process-oriented (procedure-oriented) programming. There is another way to organize your program by combining data with functionality and wrapping it in something called an "object". In most cases, you can use procedural programming, but when you need to write a large program or face a problem that is more appropriate for this approach, you might consider using object-oriented programming techniques.
  • There is only one specific difference between a class method and a normal function-the former must add a parameter (custom is called self, but can be any name) at the beginning of the argument list, the name must be added to the beginning of the argument list, but you do not have to assign a value to the parameter when you call this function, and Python will provide it.
  • When you call a method of this object, such as Myobject.method (Arg1, arg2), Python will automatically convert it to Myclass.method (MyObject, Arg1, arg2)-that's all that's special about self.
  • __init__The instantiated method runs immediately when an object of the class is instantiated (a), which is equivalent to the Java construction method.
  • field is simply a normal variable bound (Bound) to the namespace (Namespace) of the class and object. There are two types of fields (field): Class variables and object variables
  • Besides 类名.字段 , we can also use self.__class__.字段 to refer to class variables, because each object passes self. Class property to reference its classes.
  • Class methods (Classmethod) and Static methods (Staticmethod)

    class Person:    @classmethod    defid(cls):        pass

Adorners (decorator) are @classmethod equivalent to callingid = classmethod(id)

  • A field or method that begins with a double underscore is private, as is the case for classes and objects.
  • class Student(SchoolMember):Represents Student SchoolMember the child class that is. To use inheritance, define a class that needs to be followed by a tuple that contains the name of the base class.
  • If a method is defined in a subclass __init__ , the method of the parent class is not automatically called when the child class is instantiated, __init__ and the parent class is automatically called when the subclass is initialized if there is no definition in the subclass __init__ .
  • Python provides a Pickle standard module called, through which you can store any pure Python object in a file and retrieve it later. This is called persistent (persistently) storage object.
  • Encoded using UTF-8 when the first line of the program is written to # encoding=utf-8 indicate the current Python file.
  • Use to try..except..else..finally handle exceptions. The raise subclass object must be thrown with an exception thrown Exception .
    python try: text = input(‘Enter something --> ‘) except EOFError: print(‘Why did you do an EOF on me?‘) except KeyboardInterrupt as ex: print(‘You cancelled the operation.‘) else: # 如果没有异常则执行 print(‘You entered {}‘.format(text)) finally: pass

  • withStatement. Can make some finally easier to write.
    python with open("poem.txt") as f: for line in f: print(line, end=‘‘)

withGets the object F returned by the Open () and executes before the next code block executes, followed by the execution of the f.__enter__() code block f.__exit__() .

  • After familiar with the Python standard library, many things become easy.
  • Multiple assignments with tuples can also be returned with this implementation.
    python a,b = 1,2

  • Some methods in class have special meanings, and special methods are used to simulate some of the behavior of built-in classes (built-in types).
    • __init__(self, ...)
      This method was called just before the newly created object is returned for usage.
    • __del__(self)
      Called just before the object is destroyed (which have unpredictable timing, so avoid using this).
    • __str__(self)
      Called when we use the Print function or if STR () is used.
    • __lt__(self, other)
      Called when the less than operator (<) is used. Similarly, there is special methods for all the operators (+,, etc.)
    • __getitem__(self, key)
      Called when X[key] indexing operation is used.
    • __len__(self)
      Called when the built-in Len () function was used for the sequence object.
  • lambda expression :

    points =  [{ ' x ' : 2 ,  ' y ' : 3 }, { ' x ' : 4 , : 1 }]points.sort (Key=  lambda  i:i[  ' y ' ]) print  (points)  
  • List derivation (listing comprehension):

    = [234= [2*forinif>2]print(listtwo)
  • By using the * and ** prefixes you can pass a tuple and a dictionary of indeterminate elements to the function.
  • What Next. Todo

Concise Python Tutorial Notes

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.