A complete summary of Python basics (classes, objects, packages)

Source: Internet
Author: User
Tags readline

Python Basics (Classes and objects, packages)
Classes and objects
The object is seen and touched.
Class is a template
Objects require classes to be created
The composition of a class (three parts)
Name of class: class name
Class Properties: A set of data
Method of the class: The method (behavior) that allows the operation
Class name ():
Def
Add method
Class Cat ():
def run (self):
Print ("Cat is Running")
Xiaobai = Cat ()
Xiaobai.run ()
Xiaobai.name = "small white"
Xiaobai.age = 40
Properties of the class
property is a variable
A class can create multiple objects
Note Self
Class Cat ():
def intro (self):
Print ("%s%d"% (Self.name, self.age))
def run (self):
Print ("Cat is Running")
Xiaobai = Cat ()
Xiaobai.run ()
Xiaobai.name = "small white"
Xiaobai.age = 40
Xiaobai.intro ()
When you have two objects, you should pay attention to self.
InitMethod Magic Method
Procedures for creating objects
1. Create an Object
2. Automatic invocation InitMethod
3. Return a reference to the created object
Def Init(self,new_name,new_age):
Self.name = New_age
Self.age = New_age
Incoming
Xiaobai = Cat ("Lammao", 40)
New_age
New_name is a local variable
StrMethod
When using the print output object, as long as you define the Str(self) method, the data that you return from this method is printed
Hide properties of an object
The attribute is defined as a private property, and external calls are not added
Private methods
In front of the method, add

Call other methods inside a class
self+ Method Name
delMethod
Del can delete objects
When you delete an object, the Python interpreter also calls a method by default, which is del() method
Class Dog:
Def del(self):
Print ("Dead")
Dog = Dog
Dog1 = Dog
Del dog #此时不调用del方法 This object has other variables pointing to
Del Dog1 #此时调用
If some objects still exist at the end of the program, the Python interpreter automatically calls the Del method to complete the cleanup work
Import Random
Toolbox
Import Sys
Sys.getrefcount (object name)
You can see that there are several variables that point to this object reference, which is 1 larger than the actual number
Inherited
Class Animal ():
Pass
CLSS Dog (Animal):
Pass
The function subclass of the parent class can be used directly
The methods of several subclasses do not know what to call
A method of a parent class, a subclass, can also be called by a subclass of a child class
Rewrite
A method of a parent class can be written from a new class in a subclass
Call the method from the write and the original method
1. Parent class name. Method Name (Slef)
2.super (). Duplicate method Name ()
Private methods, performance of private properties (not inherited)
Private methods of the parent class private properties cannot be used directly in subclasses
If you call a public method in an inherited parent class, you can access private methods and private properties in the parent class in this public method
If a public method is implemented in a subclass, then private methods and private properties in the inherited parent class cannot be called in this method
Multiple inheritance
There are no other classes to inherit, you can write on (object) later to write on it as a new class
Not writing is called the Classic class.
Inherit multiple classes written in parentheses ()
C3 algorithm
The class name. MRO
Decide when to call a method, the order of the search, and if a method is found in a class, stop the search
Polymorphic
When you call a method, you do not know whether the call is a subclass or a parent class
The subclass parent of the call cannot be found until it is called
Class Dog (object):
def print_self (self):
Print ("Hello everyone, I am xxx, I hope you have a lot of care")
Class XIAOTQ (Dog):
def print_self (self):
Print ("Hello,everybody")
def introduce (temp):
Temp.print_self ()
Dog1 = Dog ()
DOG2 = XIAOTQ ()
Introduce (DOG1)
Introduce (DOG2)
Class properties and Instance properties
If you need to modify the class properties outside of the class, you must refer to the class object and then modify it. If a reference is made through an instance object, it produces an instance property of the same name, which modifies the instance property, does not affect the Class property, and then, if the property of that name is referenced by the instance object, the instance property forces the class property to be masked, that is, the instance property is referenced unless the instance property is deleted.
@classmethod class methods and instance methods br/> @staticmethod static methods
NewMethod
Class A (object):
Def Init(self):
Print ("This is the Init method")
Def New(CLS):
Print ("This is the new method")
Return object. New(CLS)
A ()
Attention:
NewThere must be at least one parameter CLS, which represents the class to instantiate, which is automatically provided by the Python interpreter when instantiated
NewMust have a return value that returns an instantiated instance, which is implemented on its own NewPay special attention when you return to the parent class NewOut of the instance, or is directly an object NewOut of the instance
InitThere's a parameter, self, that's it. NewThe returned instance, InitIn NewCan accomplish some other initialization actions based on the InitNo return value required
We can compare classes to manufacturers, Newmethod is the purchase of raw materials in the early stage, InitThe method is to process and initialize the commodity link on the basis of raw materials.
Single-Case mode
1. Ensure that there is only one instance of a class, and instantiate it yourself and provide this instance to the quake brother system, this class becomes a singleton class, and the singleton pattern is an object-creation pattern.
Recycle Bin is the application of single case mode
2. Create a singleton to ensure that only one object
3. Only once when creating a singleton InitMethod
Exception handling
Try
Expect:
Eg.try:
Print ('-–test–1-')
Open (' 123.txt ', ' R ')
Print ('-–test–2-')
Except IOError:
Pass
Ecpect Catching multiple exceptions
Gets the description of the exception information
Try except Eles
Try...finally ... Statements are used to express such situations:
In a program, if a segment code has to be executed, that is, whether the exception is generated or not, then you need to use finally. such as file close, Release lock, return database connection to connection pool, etc.
Demo
Import time
Try
f = open (' Test.txt ')
Try
While True:
Content = F.readline ()
If len (content) = = 0:
Break
Time.sleep (2)
Print (content)
Except
#如果在读取文件的过程中, an exception is generated, and then it is captured
#比如 pressed CTRL + C.
Pass
Finally
F.close ()
Print (' Close file ')
Except
Print ("No This file")
We can observe that the keyboardinterrupt anomaly is triggered and the program exits. But before the program exits, the finally clause is still executed and the file is closed.
Try Nesting
Import time
Try
f = open (' Test.txt ')
Try
While True:
Content = F.readline ()
If len (content) = = 0:
Break
Time.sleep (2)
Print (content)
Finally
F.close ()
Print (' Close file ')
Except
Print ("No This file")
Operation Result:
in [+]: Import time
...: try:
...: F = open (' Test.txt ')
...: try:
...: While True:
...: content = F.readline ()
...: If len (content) = = 0:
...: Break
...: Time.sleep (2)
...: print (content)
...: Finally:
...: F.close ()
...: print (' Close file ')
...: except:
...: Print ("No This file")
...: Finally:
...: Print ("last finally")
...:
Xxxxxxx-> This is the information that is read in the Test.txt file
^c closing files
Without this file
The last finally
function nested call in
Import time
Try
f = open (' Test.txt ')
Try
While True:
Content = F.readline ()
If len (content) = = 0:
Break
Time.sleep (2)
Print (content)
Finally
F.close ()
Print (' Close file ')
Except
Print ("No This file")
Operation Result:
in [+]: Import time
...: try:
...: F = open (' Test.txt ')
...: try:
...: While True:
...: content = F.readline ()
...: If len (content) = = 0:
...: Break
...: Time.sleep (2)
...: print (content)
...: Finally:
...: F.close ()
...: print (' Close file ')
...: except:
...: Print ("No This file")
...: Finally:
...: Print ("last finally")
...:
Xxxxxxx-> This is the information that is read in the Test.txt file
^c closing files
Without this file
The last finally

  1. function nested call in
    def test1 ():
    Print ("--test1-1--")
    Print (num)
    Print ("--test1-2--")
    Def test2 ():
    Print ("--test2-1--")
    Test1 ()
    Print ("--test2-2--")
    def test3 ():
    Try
    Print ("--test3-1--")
    Test1 ()
    Print ("--test3-2--")
    Except Exception as result:
    Print ("An exception was caught, information is:%s"%result)
    Print ("--test3-2--")
    Test3 ()
    Print ("--Gorgeous split line-")
    Test2 ()
    If the try is nested, then if the inside try does not catch the exception, then the outside try will receive the exception, and then processing, if the outside try is still not captured, then pass ...
    If an exception is generated in a function, such as the function a--> function b--> function C, and the exception is generated in function C, then if the exception is not handled in function C, then the exception is passed to function B, If function B has exception handling then it executes according to function B, and if function B does not have exception handling, the exception will continue to pass, and so on ... If all the functions are not processed, then the exception is handled by default, which is what is usually seen
    Note that when the TEST3 function is called, an exception is generated inside the Test1 function, which is passed to the TEST3 function to complete exception handling, and when the exception is processed, it is not returned to the function Test1 to execute, but continues in the function test3
    Class Test (object):
    DefInit(self, switch):
    Self.switch = Switch #开关
    Def calc (self, A, b):
    Try
    Return A/b
    Except Exception as result:
    If Self.switch:
    Print ("Capture turned on, the exception has been caught, information is as follows:")
    Print (Result)
    Else
    #重新抛出这个异常, this exception is not captured at this time, triggering the default exception handling
    Raise
    A = Test (True)
    A.calc (11,0)
    Print ("———————-gorgeous split-line —————-")
    A.switch = False
    A.calc (11,0)
    Module
    Modules in the <1>python
    A friend with C programming experience knows that if you want to refer to the SQRT function in C, you must use the phrase # include <math.h> introduce the MATH.H header file, otherwise it cannot be called normally.
    So in Python, what if you want to refer to some other function?
    There is a concept in Python called module, which is similar to a header file in C and a package in Java, such as calling the SQRT function in Python, which must be introduced into the math module with the Import keyword. Here's a look at the modules in Python.
    The popular point: The module is like a toolkit, to use the tool in the toolkit (like a function), you need to import this module
    <2>import
    Using the keyword import in Python to introduce a module, such as referencing module math, can be introduced with import math at the very beginning of the file.
    Shaped like:
    Import Module1,mudule2 ...
    When the interpreter encounters an import statement, the module is imported if it is in the current search path.
    When you call a function in the math module, you must refer to this:
    Module name. function name
    Think about it:
    Why do I have to call the module name?
    For:
    Because there might be a situation where a function with the same name is in multiple modules, and if it is only called by the function name, the interpreter cannot know exactly which function to invoke. So if the module is introduced as described above, the calling function must add the module name
    Import Math
    #这样会报错
    Print sqrt (2)
    #这样才能正确输出结果
    Print Math.sqrt (2)
    Sometimes we just need to use a function in the module, just to introduce the function, which can be implemented in the following way:
    From Module name Import function name 1, function name 2 ....
    Not only can we introduce functions, but we can also introduce some global variables, classes, etc.
    Attention:
    When introduced in this way, only the function name can be given when the function is called, and the module name cannot be given, but when the two modules contain the same name function, the subsequent introduction overwrites the previous one. In other words, if the function function () is in module A, there is also functional function () in module B, and if you introduce the functions in the first and B functions in a, then when you call function, is to execute the function functions in module B.
    If you want to introduce everything in math at once, you can also use the From math importto achieve
    <3>from...import
    The FROM statement of Python lets you import a specified part from the module into the current namespace
    The syntax is as follows:
    From ModName import name1[, name2[, ... Namen]]
    For example, to import the Fibonacci function of a module FIB, use the following statement:
    From fib import Fibonacci
    Attention
    The entire FIB module will not be imported into the current namespace, it will only introduce the Fibonacci individual in the FIB
    <4>from ... import

    It is also possible to import all the contents of a module into the current namespace, just use the following declaration:
    From ModName Import
    Attention
    This provides an easy way to import all the items in a module. However, such statements should not be used too much.
    <5> as
    In [1]: Import time as TT
    In [2]: Time.sleep (1)
    —————————————————————————
    Nameerror Traceback (most recent)
    <ipython-input-2-07a34f5b1e42> in <module> ()
    -1 time.sleep (1)
    Nameerror:name ' time ' is not defined
    In [3]:
    In [3]:
    In [3]: Tt.sleep (1)
    In [4]:
    In [4]:
    In [4]: From time import sleep as SP
    In [5]: Sleep (1)
    —————————————————————————
    Nameerror Traceback (most recent)
    <ipython-input-5-82e5c2913b44> in <module> ()
    -1 sleep (1)
    Nameerror:name ' sleep ' is not defined
    In [6]:
    In [6]:
    In [6]: SP (1)
    In [7]:
    <6> Positioning module
    When you import a module, the Python parser's search order for the module location is:
    Current directory
    If it is not in the current directory, Python searches for each directory under the shell variable Pythonpath.
    If none are found, Python looks at the default path. Under UNIX, the default path is typically/usr/local/lib/python/
    The module search path is stored in the Sys.path variable of the system module. The variable contains the current directory, Pythonpath, and the default directory determined by the installation process.
    Calls to custom modules
    test.py
    def add (A, B)
    Return a+b
    Calling methods
    Import Test
    Form Test Import Add
    If a file has AllVariable, then it means that the element in the variable will not be import from XXX
    When importing
    Module installation, use
    1. How to Install
    Find the module's compression package
    Extract
    Go to Folder
    Execute command python setup.py install
    Attention:
    If you perform a directory installation at install time, you can use the Python setup.py install–prefix= installation path
    2. Introduction of Modules
    In the program, use the from import to complete the installation of the module
    From Module name Import module name or *
    Packages in Python
  2. Introduction Package
    1.1 has 2 modules function some connection
    1.2 So put it in the same folder
    1.3 Using the import file. How modules are imported
    1.4 Importing from the import module using the From folder
    1.5 Creating the init. py file under the MSG folder
    1.6 Writing in the init. py file
    1.7 re-importing from folder Import module
    Summarize:
    The package organizes the associated modules together, put them in the same folder, and creates a name for the init. py file in this folder, then this folder is called the package
    Effectively avoid the problem of module name conflict, make the application organization structure clearer
  3. What is the init. py file for?
    init. PY controls the import behavior of the package
    2.1 init. Py is empty
    Simply import this package and not import the modules in the package
    2.2 All
    In the init. py file, define an all variable that controls the module imported from the Package name import *
    2.3 (understanding) You can write content in the init. py file
    You can write statements in this file that are executed when you import them.
    init. py file
  4. Extensions: Nested Packages
    Let's assume that our package example has the following directory structure:
    phone/
    Init. py
    common_util.py
    voicedta/
    Init. py
    pots.py
    isdn.py
    fax/
    Init. py
    g3.py
    mobile/
    Init. py
    analog.py
    igital.py
    pager/
    Init. py
    numeric.py
    The Phone is the topmost package, VOICEDTA, etc. is its child package. We can import the child package like this:
    Import Phone.Mobile.Analog
    Phone.Mobile.Analog.dial ()
    You can also use From-import to implement different requirements of the import
    The first approach is to import only the top-level child package, and then use the attribute/point operator to reference the sub-Baoshu:
    From Phone import Mobile
    Mobile.Analog.dial (' 555-1212 ')
    In addition, we can also refer to more sub-packages:
    From Phone.mobile import Analog
    Analog.dial (' 555-1212 ')
    In fact, you can always import along the sub-package's tree structure:
    From Phone.Mobile.Analog Import dial
    Dial (' 555-1212 ')
    In our directory structure above, we can find a lot ofInit. py file. These are initialization modules that need to be used when the From-import statement imports a child package. If they are not used, they can be empty files.
    The package also supports the From-import all statement:
    From package.module Import *
    However, such a statement will import which files depend on the filesystem of the operating system. So we're inInitThe. PY Join AllVariable. The variable contains the name of the module that should be imported when executing such a statement. It consists of a list of module name strings.
    51cto Address http://blog.51cto.com/n1lixing

New Ket Cinema http://www.ldxzs.top/shipin/shipin/

Site Address: Http://www.ldxzs.top

A complete summary of Python basics (classes, objects, packages)

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.