Python学习笔记-DAY5

匿名函数()

装饰器:

偏函数

内置函数

 

匿名函数()

def f(x): 关键字lambda表示匿名函数,冒号前面的x表示函数参数

                                           return x*x匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果

print map(lambda x:x*x,[1,2,3,4,5,6])

def build(x,y):

    return lambda :x*x+y*y

f=build(3,2用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数

print f()

F=lambda x: x * x

print F(5)

装饰器:

偏函数:(Partial function)

import functools
print int('12345',base=16) #int()函数还提供额外的base参数,默认值为10
print int('12345',8)
print int('10000000',2)
def int2(x, base=2):
   
return int(x, base)
print int2('10000000')
int3=functools.partial(
int ,base=2) functools.partial帮助我们创建一个偏函数,不需要我们自己定义int2(),
print int3('10000000')
max2=functools.partial(
max,10) 创建偏函数时,实际上可以接收函数对象、*args**kw3个参数,当传入max2=functools.partial(max,10),实际上会
print max2(5,6,7)                   把10作为*args的一部分自动加到左边,也就是max2(5,6,7)相当于:args=(10,5,6,7) max(*args)
print max(range(10))
print max2(range(10))
print max2(0,1,2,3,4,5,6,7,8,9)
def f(x):
   
print x
g=functools.partial(f,
x=2)
g(
x=3)

def fun(x,y,z,t):
   
print 'x=%s,y=%s,z=%s,t=%s'%(x,y,z,t)
fun01=functools.partial(fun,
y=2,t=3)
fun01(
x=10,z=8)

模块:

内置函数:

  1. basestring():This abstract type is the superclass for str and unicode.

basestring=(str,unicode)

  1. bin(x): Convert an integer number to a binary string

print bin(100

  1. class bool([x]): Return a Boolean value,

print bool(1)

  1. class bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is unicode, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the unicode to bytes using unicode.encode().
  • If it is an integer, the array will have that size and will be initialized with null bytes.
  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

  1. callable(object)

Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a__call__() method.

  1. chr(i)

Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range. See also unichr().

print chr(97)
print ord('a')
print chr(255)
print chr(256)

  1. classmethod(function)

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C(object):

    @classmethod

    def f(cls, arg1, arg2, ...):

        ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

  1. cmp(xy)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

print cmp(1,2)
print cmp(1,1)
print cmp(2,1)
print cmp('abc','bbc')

  1. compile(sourcefilenamemode[, flags[, dont_inherit]])

Compile the source into a code or AST object.

  1. class complex([real[imag]])

Return a complex number with the value real + imag*1j or convert a string or number to a complex number.

  1. delattr(objectname)

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.

class dict(**kwarg)

class dict(mapping**kwarg)

class dict(iterable**kwarg)

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in listset, and tuple classes, as well as the collections module.

  1. dir([object]):

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

  1. divmod(ab):
    Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division

print divmod(100,21)

 

 

  1. enumerate(sequencestart=0)

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next()method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

seasons=['Spring','Summer','Fall','Winter']
print list(enumerate(seasons))
print list(enumerate(seasons,start=1))

  1. eval(expression[globals[, locals]])

The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

x=1
print eval('x+1')

  1. execfile(filename[globals[, locals]])

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module. [1]

  1. file(name[mode[buffering]]):

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

  1. format(value[format_spec])

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

format(value, format_spec) merely calls value.__format__(format_spec).

from datetime import datetime
print '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

 

 

猜你喜欢

转载自blog.csdn.net/yige__cxy/article/details/81169563