Python Learning Note 3

Source: Internet
Author: User

9 Higher order functions

(1) the map () function receives two parameters, one is the function, and the other is iterable,map the incoming function to each element of the sequence, and returns the result as a new iterator.list(map(str, [1, 2, 3]))

(2) Reduce a function in a sequence [X1, x2, x3, ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.from functools import reduce

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

(3) filter () also receives a function and a sequence. Filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false. filter()the function returns a Iterator .

(4) sorted () sortsorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower, reverse=True)

10 Functional programming

(1) The higher order function can also return the function as the result value, in addition to being able to accept the function as a parameter.

Call the lazy_sum() return function, the inner function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are saved in the returned function, called closures.

The returned function is not executed immediately, and f=lazy_sum (All-in-all) calls the F () function.

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

If you must refer to a loop variable, you can create a function that binds the current value of the loop variable with the parameter of the function, regardless of how the loop variable is subsequently changed, and the value that is bound to the function parameter remains the same.

def lazy_sum(*args):    def sum(): ax=0 for n in args: ax=ax+n return ax return sum

(2) anonymous function, the keyword lambda represents an anonymous function, the x preceding the colon represents a function parameter, and the colon is followed by an expression.lambda x: x * x

(3) Decorative device

(4) Partial function, when the number of parameters of the function is too many, need to simplify, use functools.partial can create a new function, the new function can be fixed in the original function part of the parameters, making it easier to call.

11 modules

Each package directory will have a __init__.py file, this file must exist, otherwise, Python will treat this directory as a normal directory, rather than a package.

__init__.pyIt can be an empty file, or it can have Python code, because it __init__.py is a module in itself.

A __xxx__ variable like this is a special variable that can be referenced directly, but has a special purpose, for example, the above __author__,__name__ is a special variable.

Similar _xxx and __xxx such functions or variables are non-public (private), should not be directly referenced, such as _abc,__abc ;

Class 12

(1) Because the class can play the role of a template, you can create an instance by forcing some of the attributes that we think must be bound to be filled in.

By defining a special __init__ method. __init__The first argument of a method is always self, which represents the created instance itself ,

Therefore, within a __init__ method, you can bind various properties to self, because the individual points to the created instance itself.

method is the function that binds to the instance, and the normal function is different, the method can directly access the data of the instance;

Unlike static languages, Python allows binding on instance variables of any property, such as bart.age .

class Student(object):    def __init__(self, name, score): self.name = name self.score = score def print_score(self): print(‘%s: %s‘ % (self.name, self.score))bart = Student(‘Bart Simpson‘, 59)bart.age=12

(2) If you want the internal properties not to be accessed externally, the name of the property can be preceded by two underscores __ ,

In Python, if the variable name of an instance __ begins with a private variable (private) self.__name=name , the external code gets the name, which adds a method to the student class.

(3) Inheritance can take all the functions of the parent class directly, subclasses only need to add their own unique methods, but also the parent class does not fit the method overrides overrides.

(4) Isinstance () determines whether an object is the type itself, or is located on the parent inheritance chain of that type. isinstance([1, 2, 3], (list, tuple) ;

The Dir () function obtains all the property methods of an object;

GetAttr (), SetAttr (), and hasattr () can manipulate the properties or methods of an object directly;getattr(obj, ‘z‘, 404) # 获取属性‘z‘,如果不存在,返回默认值404

(5) Class property, defined directly in class. Instance properties of the same name are masked out of class properties.

(6) Bind a method to an instance,

s = Student()def qage(self,age):    self.age=agefrom types import MethodTypes.age=MethodType(qage,s)s.age(9)

When you bind a method to a class, all instances can call theStudent.qage=qage

To restrict the properties of an instance, define a special variable when defining class __slots__ to limit the attributes that the class instance can add.class Student(object):

     __slots__ = (‘name‘, ‘age‘) # 用tuple定义允许绑定的属性名称

_slots__The defined property only works on the current class instance and does not work on the inherited subclass, unless it is also defined in the subclass _slots__ so that the subclass instance allows the defined property to be its own _slots__ plus the 'slots_' of the parent class.

(7) Python's built-in @property decorator is responsible for turning a method into a property invocation.

class Span class= "Hljs-title" >student (object):  @property def age ( Self): return self.__age  @age setter def age  (self,value): if not isinstance ( Value,int): raise valueerror ( ' wrong ') self.__age=value  

(8) __str__: Print out the example, not only good-looking, but also easy to see the important data inside the instance. The direct display of the variable is not called __str__() but__repr__()

The difference is that it returns the string that the __str__() user sees and __repr__() returns the string that the program developer sees, that is, the __repr__() service for debugging. __repr__()can be displayed directly after definition.

class a(object):    def __init__(self,name): self.__name=name def __str__(self): return ‘hello %s‘%self.__name __repr__=__str__

Python Learning Note 3

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.