目录

Python内置函数

数学运算

  • abs:绝对值
1
2
3
def abs(*args, **kwargs): # real signature unknown
    """ Return the absolute value of the argument. """
    pass
1
2
>>>abs(-4)
4
  • divmod:返回两个数值的商和余数
1
2
3
def divmod(x, y): # known case of builtins.divmod
    """ Return the tuple (x//y, x%y).  Invariant: div*y + mod == x. """
    return (0, 0)
1
2
3
4
>>>divmod(7,2)
(3, 1)
>>>divmod(7,1.5)
(4.0, 1.0)
  • max:返回可迭代对象中的元素中的最大值或者所有参数的最大值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass
1
2
3
4
5
6
7
8
>>> max(1,2,3) # 传入3个参数 取3个中较大者
3
>>> max('1234') # 传入1个可迭代对象,取其最大元素值
'4'
>>> max(-1,0) # 数值默认去数值较大者
0
>>> max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1
  • min:返回可迭代对象中的元素中的最小值或者所有参数的最小值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def min(*args, key=None): # known special case of min
    """
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.
    """
    pass
    """ Return the absolute value of the argument. """
    pass
1
2
3
4
5
6
7
8
>>> min(1,2,3) # 传入3个参数 取3个中较小者
1
>>> min('1234') # 传入1个可迭代对象,取其最小元素值
'1'
>>> min(-1,-2) # 数值默认去数值较小者
-2
>>> min(-1,-2,key = abs)  # 传入了求绝对值函数,则参数都会进行求绝对值后再取较小者
-1
  • pow:返回两个数值的幂运算值或其与指定整数的模值
1
2
3
4
5
6
7
8
def pow(*args, **kwargs): # real signature unknown
    """
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
    """
    pass
1
2
3
4
5
>>> pow(2,3)
>>> 8
>>>
>>> pow(2,3,5)
>>> 3
  • round:对浮点数四舍五入
1
2
3
4
5
6
7
8
9
def round(number, ndigits=None): # real signature unknown; restored from __doc__
    """
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.
    """
    return 0
1
2
3
4
>>>round(4.33)
4
>>>>round(1.44443326,4)
1.4444
  • sum:对元素类型是数值的可迭代对象中的每个元素求和
1
2
3
4
5
6
7
8
9
def sum(*args, **kwargs): # real signature unknown
    """
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
    """
    pass
1
2
3
4
5
6
>>> sum((1,2,3,4))  # 传入可迭代对象
10
>>> sum((1.5,2.5,3.5,4.5))  # 元素类型必须是数值型
12.0
>>> sum((1,2,3,4),-10)
0

类型转换

  • bool:根据传入的参数的逻辑值创建一个新的布尔值
1
2
    def __init__(self, x): # real signature unknown; restored from __doc__
        pass
1
2
3
4
5
6
>>> bool() #未传入参数
False
>>> bool(0) #数值0、空序列等值为False
False
>>> bool(1)
True
  • int:根据传入的参数创建一个新的整数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
        def __init__(self, x, base=10): # known special case of int.__init__
        """
        int(x=0) -> integer
        int(x, base=10) -> integer

        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.

        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)
        """
        pass
1
2
3
4
5
6
>>> int() #不传入参数时,得到结果0。
0
>>> int(3)
3
>>> int(3.6)
3
  • float:根据传入的参数创建一个新的浮点数
1
2
3
4
5
6
>>> float() #不提供参数的时候,返回0.0
0.0
>>> float(3)
3.0
>>> float('3')
3.0
  • complex:根据传入参数创建一个新的复数
1
2
3
4
5
6
>>> complex() #当两个参数都不提供时,返回复数 0j。
0j
>>> complex('1+2j') #传入字符串创建复数
(1+2j)
>>> complex(1,2) #传入数值创建复数
(1+2j)
  • str:返回一个对象的字符串表现形式(给用户)
1
2
3
4
5
6
7
8
>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'
  • bytearray:根据传入的参数创建一个新的字节数组
1
2
>>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
  • bytes:根据传入的参数创建一个新的不可变字节数组
1
2
>>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
  • memoryview:根据传入的参数创建一个新的内存查看对象
1
2
3
4
5
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
  • ord:返回Unicode字符对应的整数
1
2
3
def ord(*args, **kwargs): # real signature unknown
    """ Return the Unicode code point for a one-character string. """
    pass
1
2
>>> ord('a')
97
  • chr:返回整数所对应的Unicode字符
1
2
3
def chr(*args, **kwargs): # real signature unknown
    """ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """
    pass
1
2
>>> chr(97) #参数类型为整数
'a'
  • bin:将整数转换成2进制字符串
1
2
3
4
5
6
7
8
def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the binary representation of an integer.

       >>> bin(2796202)
       '0b1010101010101010101010'
    """
    pass
1
2
>>> bin(3)
'0b11'
  • oct:将整数转化成8进制数字符串
1
2
3
4
5
6
7
8
def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the octal representation of an integer.

       >>> oct(342391)
       '0o1234567'
    """
    pass
1
2
>>> oct(10)
'0o12'
  • hex:将整数转换成16进制字符串
1
2
3
4
5
6
7
8
def hex(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the hexadecimal representation of an integer.

       >>> hex(12648430)
       '0xc0ffee'
    """
    pass
1
2
>>> hex(15)
'0xf'
  • tuple:根据传入的参数创建一个新的元组
1
2
3
4
>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121') #传入可迭代对象。使用其元素创建新的元组
('1', '2', '1')
  • list:根据传入的参数创建一个新的列表
1
2
3
4
>>>list() # 不传入参数,创建空列表
[]
>>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a', 'b', 'c', 'd']
  • dict:根据传入的参数创建一个新的字典
1
2
3
4
5
6
7
8
>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1,b = 2) #  可以传入键值对创建字典。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以传入映射函数创建字典。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以传入可迭代对象创建字典。
{'b': 2, 'a': 1}
  • set:根据传入的参数创建一个新的集合
1
2
3
4
5
>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  • frozenset:根据传入的参数创建一个新的不可变集合
1
2
3
>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
  • enumerate:根据可迭代对象创建枚举对象
1
2
3
4
5
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • range:根据传入的参数创建一个新的range对象
1
2
3
4
5
6
7
8
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分别输出a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # 分别输出a,b,c的元素
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])
>>>
  • iter:根据传入的参数创建一个新的可迭代对象
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def iter(source, sentinel=None): # known special case of iter
    """
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator

    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> a = iter('abcd') #字符串序列
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    next(a)
StopIteration
  • slice:根据传入的参数创建一个新的切片对象
1
2
3
4
5
6
7
8
9
>>> c1 = slice(5) # 定义c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) # 定义c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) # 定义c3
>>> c3
slice(1, 10, 3)
  • super:根据传入的参数创建一个新的子类和父类关系的代理对象
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
    def __init__(self, type1=None, type2=None): # known special case of super.__init__
        """
        super() -> same as super(__class__, <first argument>)
        super(type) -> unbound super object
        super(type, obj) -> bound super object; requires isinstance(obj, type)
        super(type, type2) -> bound super object; requires issubclass(type2, type)
        Typical use to call a cooperative superclass method:
        class C(B):
            def meth(self, arg):
                super().meth(arg)
        This works for class methods too:
        class C(B):
            @classmethod
            def cmeth(cls, arg):
                super().cmeth(arg)

        # (copied from class doc)
        """
        pass
1
2
3
4
5
6
7
>>> class A(object):
    def __init__(self):
        print('A.__init__')
>>> class B(A):
    def __init__(self):
        print('B.__init__')
        super().__init__()
  • object:创建一个新的object对象
1
2
3
4
5
6
>>> a = object()
>>> a.name = 'kim' # 不能设置属性
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    a.name = 'kim'
AttributeError: 'object' object has no attribute 'name'

序列操作

  • help:返回对象的帮助信息
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
>>> help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
  ***************************
  • dir:返回对象或者当前作用域内的属性列表
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def dir(p_object=None): # real signature unknown; restored from __doc__
    """
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
    """
    return []
1
2
3
4
5
6
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
'0xf'
  • id:返回对象的唯一标识符
1
2
3
4
5
6
7
8
def id(*args, **kwargs): # real signature unknown
    """
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)
    """
    pass
1
2
3
>>> a = "test"
>>> id(a)
1621561598112
  • hash:获取对象的哈希值
1
2
3
4
5
6
7
8
def hash(*args, **kwargs): # real signature unknown
    """
    Return the hash value for the given object.

    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.
    """
    pass
1
2
>>> hash('study')
-3947515207446763768
  • type:返回对象的类型,或者根据传入的参数创建一个新的类型
1
2
3
4
5
6
7
8
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
    """
    type(object_or_name, bases, dict)
    type(object) -> the object's type
    type(name, bases, dict) -> a new type
    # (copied from class doc)
    """
    pass
1
2
3
4
5
6
7
8
>>> type(1) # 返回对象的类型
<class 'int'>

#使用type函数创建类型D,含有属性InfoD
>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))
>>> d = D()
>>> d.InfoD
'some thing defined in D'
  • len:返回对象的长度
1
2
3
def len(*args, **kwargs): # real signature unknown
    """ Return the number of items in a container. """
    pass
1
2
3
4
5
6
7
8
>>> len('abcd') # 字符串
>>> len(bytes('abcd','utf-8')) # 字节数组
>>> len((1,2,3,4)) # 元组
>>> len([1,2,3,4]) # 列表
>>> len(range(1,5)) # range对象
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
>>> len({'a','b','c','d'}) # 集合
>>> len(frozenset('abcd')) #不可变集合
  • ascii:返回对象的可打印表字符串表现方式
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def ascii(*args, **kwargs): # real signature unknown
    """
    Return an ASCII-only representation of an object.

    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \\x, \\u or \\U escapes. This generates a string similar
    to that returned by repr() in Python 2.
    """
    pass
1
2
3
4
5
6
7
8
>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii('中文') #非ascii字符
"'\\u4e2d\\u6587'"
  • format:格式化显示值
1
2
3
4
5
6
7
def format(*args, **kwargs): # real signature unknown
    """
    Return value.__format__(format_spec)

    format_spec defaults to the empty string
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#字符串可以提供的参数 's' None
>>> format('some string','s')
'some string'
>>> format('some string')
'some string'

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'

#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科学计数法,默认保留6位小数
'3.141593e+08'
>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
'3.14e+08'
>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E+08'
>>> format(314159267,'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
'INF'

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
  • vars:返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表
1
2
3
4
5
6
7
8
def vars(p_object=None): # real signature unknown; restored from __doc__
    """
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.
    """
    return {}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#作用于类实例
>>> class A(object):
    pass

>>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = 'Kim'
>>> a.__dict__
{'name': 'Kim'}
>>> vars(a)
{'name': 'Kim'}

反射操作

  • __import__:动态导入模块
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module

    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use it is better to use
    importlib.import_module() to programmatically import a module.

    The globals argument is only used to determine the context;
    they are not modified.  The locals argument is unused.  The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty.  Level is used to determine whether to perform 
    absolute or relative imports. 0 is absolute while a positive number
    is the number of parent directories to search relative to the current module.
    """
    pass
1
2
index = __import__('index')
index.sayHello()
  • isinstance:判断对象是否是类或者类型元组中任意类元素的实例
1
2
3
4
5
6
7
8
9
def isinstance(x, A_tuple): # real signature unknown; restored from __doc__
    """
    Return whether an object is an instance of a class or of a subclass thereof.

    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.
    """
    pass
1
2
3
4
5
6
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True
  • issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类
1
2
3
4
5
6
7
8
9
def issubclass(x, A_tuple): # real signature unknown; restored from __doc__
    """
    Return whether 'cls' is a derived from another class or is the same class.

    A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
    or ...`` etc.
    """
    pass
1
2
3
4
5
6
7
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False

>>> issubclass(bool,(str,int))
True
  • hasattr:检查对象是否含有属性
1
2
3
4
5
6
7
def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.

    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#定义类A
>>> class Student:
    def __init__(self,name):
        self.name = name


>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name属性
True
>>> hasattr(s,'age') #a不含有age属性
False
  • getattr:获取对象的属性值
1
2
3
4
5
6
7
8
9
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,'name') #存在属性name
'Aim'

>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值

>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
  • setattr:设置对象的属性值
1
2
3
4
5
6
7
def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.

    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> class Student:
    def __init__(self,name):
        self.name = name


>>> a = Student('xie')
>>> a.name
'xie'
>>> setattr(a,'name','wang')
>>> a.name
'wang'
  • delattr:删除对象的属性
1
2
3
4
5
6
7
def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.

    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#定义类A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print('hello',self.name)

#测试属性和方法
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦

#删除属性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
  • callable:检测对象是否可被调用
1
2
3
4
5
6
7
8
def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
    """
    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a
    __call__() method.
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> class B: #定义类B
    def __call__(self):
        print('instances are callable now.')


>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

变量操作

  • globals:返回当前作用域内的全局变量和其值组成的字典
1
2
3
4
5
6
7
8
def globals(*args, **kwargs): # real signature unknown
    """
    Return the dictionary containing the current scope's global variables.

    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.
    """
    pass
1
2
3
4
5
>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
  • locals:返回当前作用域内的局部变量和其值组成的字典
1
2
3
4
5
6
7
8
9
def locals(*args, **kwargs): # real signature unknown
    """
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.
    """
    pass
1
2
3
4
5
>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

交互操作

  • print:向标准输出对象打印输出
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass
1
2
3
4
5
6
>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?
  • input:读取用户输入值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def input(*args, **kwargs): # real signature unknown
    """
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
    """
    pass
1
2
3
4
>>> s = input('please input your name:')
please input your name:Xie
>>> s
'Xie'

编译执行

  • compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def compile(*args, **kwargs): # real signature unknown
    """
    Compile source into a code object that can be executed by exec() or eval().

    The source code may represent a Python module, statement or expression.
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if true, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or false these statements do influence the compilation,
    in addition to any features explicitly specified.
    """
    pass
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
  • eval:执行动态表达式求值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def eval(*args, **kwargs): # real signature unknown
    """
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    """
    pass
1
2
>>> eval('1+2+3+4')
10
  • exec:执行动态语句块
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def exec(*args, **kwargs): # real signature unknown
    """
    Execute the given source in the context of globals and locals.

    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    """
    pass
1
2
3
>>> exec('a=1+2') #执行语句
>>> a
3
  • repr:返回一个对象的字符串表现形式(给解释器)
1
2
3
4
5
6
7
def repr(obj): # real signature unknown; restored from __doc__
    """
    Return the canonical string representation of the object.

    For many object types, including most builtins, eval(repr(obj)) == obj.
    """
    pass
1
2
3
4
5
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

装饰器

  • property:标示属性的装饰器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class property(object):
    """
    property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

    fget is a function to be used for getting an attribute value, and likewise
    fset is a function for setting, and fdel a function for del'ing, an
    attribute.  Typical use is to define a managed attribute x:

    class C(object):
        def getx(self): return self._x
        def setx(self, value): self._x = value
        def delx(self): del self._x
        x = property(getx, setx, delx, "I'm the 'x' property.")

    Decorators make defining new properties or modifying existing ones easy:

    class C(object):
        @property
        def x(self):
            "I am the 'x' property."
            return self._x
        @x.setter
        def x(self, value):
            self._x = value
        @x.deleter
        def x(self):
            del self._x
    """
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
>>> class C:
    def __init__(self):
        self._name = ''
    @property
    def name(self):
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value


>>> c = C()

>>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    c.name = None
  File "<pyshell#81>", line 11, in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None

>>> c.name = 'Xie' # 设置属性
>>> c.name # 访问属性
'Xie'

>>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'Xie'
  • classmethod:标示方法为类方法的装饰器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class classmethod(object):
    """
    classmethod(function) -> method

    Convert a function to be a class method.

    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:
          @classmethod
          def f(cls, arg1, arg2, ...):
              ...

    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. 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 the staticmethod builtin.
    """
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)


>>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法

>>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法
  • staticmethod:标示方法为静态方法的装饰器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class staticmethod(object):
    """
    staticmethod(function) -> method

    Convert a function to be a static method.

    A static method does not receive an implicit first argument.
    To declare a static method, use this idiom:

         class C:
             @staticmethod
             def f(arg1, arg2, ...):
                 ...

    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()).  The instance is ignored except for its class.

    Static methods in Python are similar to those found in Java or C++.
    For a more advanced concept, see the classmethod builtin.
    """
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')


>>> Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome!

>>> b = Student('Xie')
>>> b.sayHello('wang')  #类实例对象调用,'zh'传给了lang参数
wang
你好