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))

 

 

Python中,异常处理是非常重要的一部分。当程序运行时如果出现错误,如果没有异常处理,程序就会崩溃。为了避免这种情况,Python提供了异常处理机制。 在Python中,异常处理语句使用 `try` 和 `except` 关键字来实现。`try` 语句块中包含可能会发生异常的代码,如果这段代码出现了异常,则会跳转到 `except` 语句块中执行异常处理代码。 下面是一个简单的例子: ```python try: num = int(input("请输入一个整数:")) print(10/num) except ZeroDivisionError: print("除数不能为0") except ValueError: print("输入的不是整数") ``` 在上面的代码中,我们尝试将用户输入的字符串转换为整数,并将其用作除数计算 10/num。如果用户输入的是 0,则会触发 ZeroDivisionError 异常。如果用户输入的不是整数,则会触发 ValueError 异常。如果发生异常,则会跳转到对应的 except 语句块中执行处理代码。 除了可以指定具体的异常类型,也可以使用 `except Exception` 来捕获所有异常。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) ``` 在上面的代码中,如果发生任何异常,都会跳转到 `except` 语句块中执行处理代码,并将异常信息打印出来。 除了 `try` 和 `except`,还有 `finally` 关键字,它指定的代码块无论是否发生异常都会执行。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) finally: print("程序执行完毕") ``` 在上面的代码中,无论是否发生异常,都会执行 `finally` 中的代码,即输出“程序执行完毕”。 总之,在Python中,异常处理是非常重要的一部分,它可以有效避免程序崩溃,提高程序的健壮性和可靠性。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值