Python functional programming and object-oriented programming

Source: Internet
Author: User
Tags closure for in range manual writing ming

function-type programming

Functions: function.
Functional type: Functional, a programming paradigm. Functional programming is an abstract computer programming mode.
Function! = Functional (such as calculation!) = computer)

The following are different levels of abstraction in different languages


 
    • Higher order functions

Functions that can receive functions for parameters:

1. Variables can point to functions
2. Parameters of function can receive variables
3. One function can receive another function as a parameter

Example

Receive ABS function, define a function, receive three x, Y, z parameters. where x, Y is a number and Z is a function.

def Add (x, y    , z): return z (x) +Z (y)print Add ( -2,-3,abs)

Other high-order functions: map()函数、reduce()函数、filter()函数 .

The Ps:python function can return the int、str、list、dict function as well as the data type.

Closed Package

Such an inner layer function refers to a variable of the outer function (parameter is also a variable), and then returns the case of the inner layer function, called the closure (Closure).

The feature is that the returned function also refers to the local variables of the outer function, so to properly use closures, it is necessary to ensure that the referenced local variables do not change after the function returns. Examples are as follows:

# you want to return 3 functions at a time, calculate 1x1,2x2,3x3 separately: def count ():     = []    for in range (1, 4):        def  F ():               return i*i        fs.append (f)    return= count ()

You might think that calling F1 (), F2 (), and F3 () results should be 1,4,9, but the actual results are all 9 (please do your own verification).

The reason is that when the count () function returns 3 functions, the value of the variable I referenced by these 3 functions has become 3. Since F1, F2, F3 are not called, they do not calculate i*i at this time, when F1 is invoked:

>>> F1 ()9     #  Because F1 now calculates i*i, but now the value of I has changed to 3.

Therefore, the return function does not refer to any loop variables, or to subsequent variables that change.

anonymous function (lambda)
>>> map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]

The comparison shows that the anonymous function lambda x:x * x is actually:

def f (x):     return x * x

The keyword lambda represents the anonymous function, and the x in front of the colon indicates the function parameter (the anonymous function has a limit, that is, there can be only one expression, no return, the return value is the result of the expression, return the function, you can return the anonymous function.) )

Adorner Decorator

Python's decorator is essentially a high-order function that takes a function as an argument and then returns a new function.

Use decorator with the @ syntax provided by Python, which avoids the manual writing of f = decorate (f) code, greatly simplifying Python code.


 Module

Import the module that comes with the system math:

Import Math

If we only want to import some of the functions of the math module used, instead of all the functions, you can use the following statement:

 from import pow, sin, log

What if I encounter a name conflict?

If you import the module name using import, there is no conflict because the function name must be referenced by the module name;

If you from...import use log the import function, it is bound to cause a conflict. At this point, you can give the function an "alias" to avoid the conflict:

 from Import Log  from Import log as Logger   #  logging log now becomes loggerprint log     called Math's log'import from logging')   #  The logging log is called .

Dynamic Import Module

The following code attempts to import from cStringIO the first, if it fails (for example, it is cStringIO not installed), then try to import from it StringIO .

Try :      from Import Stringio except importerror:      from Import Stringio

Use import ... as ... , you can also dynamically import modules of different names

Try :     Import JSON except importerror:     import Simplejson as JSON

Ps:

    1. New versions of Python introduce new features, but in fact these features already exist in the previous version. To "try out" a new feature, you can do so by importing __future__ some of the features of the module.
    2. How to differentiate between a package and a normal directory: there is a layer below the package __init__.py .
Object-Oriented programming

Defining classes and creating instances

Define a person class as follows

class Person (object):     Pass

(object) that represents the class from which the class inherits.

Create an instance

Xiaoming = person ()

How do I get each instance to have its own different properties?

Because Python is a dynamic language, for each instance, you can assign values directly to their properties, for example, by xiaoming adding attributes to the instance name、gender和birth :

Xiaoming ='Xiao Ming'Male'   '1990-1-1'

xiaohongthe attributes to be added are not necessarily the xiaoming same as:

Xiaohong ='Xiao Hong'No. 1 High School'  = 2

' The properties of an instance can be manipulated like normal variables:

Xiaohong.grade = Xiaohong.grade + 1

Initializing instance Properties

class Person (object):     def __init__ (self, name, gender, birth):         = name        = gender        = Birth

__init__()The first parameter of the method must be self (or use a different name, but the customary usage is recommended). Subsequent parameters are freely specified, and there is no difference between defining the function.

Accordingly, when you create an instance, you must provide parameters other than self:

Xiaoming = person ('Xiao Ming'Male'1991-1-1  ' = person (' Xiao Hong ' Female ' ' 1992-2-2 ')

Defining instance methods

class Person (object):     def __init__ (self, name): Self        . __name = name      def# Its first argument is always self        , pointing to the instance that called the method return self. __name

Defining class Methods (Java-like static methods)

 class   Person (object): Count  = 0 @classmethod  de F  How_many (CLS): #   return   Cls.count  def  __init__   (self, name): Self.name  =< Span style= "COLOR: #000000" > name Person.count  = person.count + 1 print  Span style= "COLOR: #000000" > Person.how_many () P1  = person ( " bob  "  )  print  person.how_many ()  

Access restrictions

If an attribute starts with a double underscore (__), the property cannot be accessed externally (equivalent to private). However, if a property is "__xxx__" defined in the form of an attribute, then it can be accessed externally, the "__xxx__" defined properties are called Special properties in the Python class, there are many predefined special attributes that can be used, and usually we do not define the ordinary attributes "__xxx__" .

    • Topic

Define the method of the person class, and accept __init__ any keyword arguments in addition to the acceptance name、gender 和 birth , and assign them all as attributes to the instance.
To define keyword parameters, use **kw ;
In addition to self.name = ‘xxx‘ setting a property directly, you can also setattr(self, ‘name‘, ‘xxx‘) set properties by setting it.

    • Reference code:
classPerson (object):def __init__(Self, name, gender, birth, * *kw): Self.name=name Self.gender=Gender Self.birth=Birth forKvinchKw.iteritems (): SetAttr (self, k, v) xiaoming= Person ('Xiao Ming','Male','1990-1-1', job='Student')PrintXiaoming.namePrintXiaoming.job
Inheritance of Classes

Inherit a class

class Person (object):     def __init__ (self, Name, gender):         = name        = Gender

When defining the Student class, you only need to add additional attributes, such as score:

class Student (person):     def __init__ (self, name, gender, score):        super (Student, self). __init__ (name, gender)         = Score

Be sure to super(Student, self).__init__(name, gender) initialize the parent class, otherwise the inherited from Person Student will not name 和 gender . The function super(Student, self) returns the parent class that is inherited by the current class, that is Person , then calls the __init__() method, notes that the self parameter is passed in super() , implicitly passes in, __init__() and does not need to write (nor write)

Judging type

The function isinstance () can determine the type of a variable

>>> isinstance (p, person)

Get object Information

In addition isinstance() to judging whether it is a certain type of instance, the type () function gets the variable's kind, which returns a type object. You can use dir() a function to get all the properties of a variable: dir(s) .

Python functional programming and object-oriented programming

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.