Python内置函数(7)

Python内置函数(1)— abs()、all()、any()、ascii()、bin()、bool()、breakpoint()、bytearray()、bytes()、callable()。
Python内置函数(2)— chr()、classmethod()、compile()、complex()、delattr()、dict()、dir()、divmod()、enumerate()、eval()。
Python内置函数(3)— exec()、filter()、float()、format()、frozenset()、getattr()、globals()、hasattr()、hash()、help()。
Python内置函数(4)— hex()、id()、input()、int()、isinstance()、issubclass、iter()、len()、list()、locals()。
Python内置函数(5)— map()、max()、memoryview()、min()、next()、object()、oct()、open()、ord()、pow()。
Python内置函数(6)— print()、property()、range()、repr()、reversed()、round()、set()、setattr()、slice()、sorted()。
Python内置函数(7)— staticmethod()、str()、sum()、super()、tuple()、type()、vars()、zip()、__import__()。

内置函数(原文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
内置函数(中文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
Python内置函数.png

61、staticmethod()

a)描述

staticmethod 返回函数的静态方法。
该方法不强制要求传递参数,如下声明一个静态方法:

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

以上实例声明了静态方法 f,从而可以实现实例化使用 C().f(),当然也可以不实例化调用该方法 C.f()。

b)语法

staticmethod的语法:staticmethod(function)

c)参数

无。

d)返回值

无。

e)实例

实例1:

class C(object):
    @staticmethod
    def f():
        print('kevin');
C.f();  # 静态方法无需实例化
cobj = C()
cobj.f()  # 也可以实例化后调用

运行结果:

kevin
kevin

实例2(staticmethod 参数要求是 Callable, 也就是说 Class 也是可以的):

class C1(object):
    @staticmethod
    class C2(object):
        def __init__(self, val = 1):
            self.val = val
        def shout(self):
            print("Python世界第%d!"%self.val)
tmp = C1.C2(0)
print(type(tmp))    # 输出 : 
tmp.shout()         # 输出 : Python世界第0!

运行结果:


Python世界第0!

62、str()

a)描述

str() 函数将对象转化为适于人阅读的形式。

b)语法

str() 方法的语法:class str(object='')

c)参数

object:对象。

d)返回值

返回一个对象的string格式。

e)实例
s = 'Kevin'
print("str(s):",str(s))
dict = {'kevin': 'kevin.com', 'google': 'google.com'};
print("str(dict):",str(dict))

运行结果:

str(s): Kevin
str(dict): {'kevin': 'kevin.com', 'google': 'google.com'}

63、sum()

a)描述

原文:
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.
中文:
返回一个'start'值(默认值为0)和一个可迭代的数字的总和。
当iterable为空时,返回初始值。
此函数专门用于数值类型,可以拒绝非数值类型。
诠释:
sum() 方法对系列进行求和计算。

b)语法

sum() 方法的语法:sum(iterable[, start])

c)参数

iterable:可迭代对象,如:列表、元组、集合。
start:指定相加的参数,如果没有设置这个值,默认为0。

d)返回值

返回计算结果。

e)实例
print("sum([0,1,2]):",sum([0,1,2]))
print("sum((2, 3, 4), 1):",sum((2, 3, 4), 1))        # 元组计算总和后再加 1
print("sum([0,1,2,3,4], 2):",sum([0,1,2,3,4], 2))      # 列表计算总和后再加 2

运行结果:

sum([0,1,2]): 3
sum((2, 3, 4), 1): 10
sum([0,1,2,3,4], 2): 12

64、super()

a)描述

super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

b)语法

super() 方法的语法:super(type[, object-or-type])

c)参数

type:类。
object-or-type:类,一般是 self

d)返回值

无。

e)实例

实例1:

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print('Parent')
    def bar(self, message):
        print("%s from Parent" % message)
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild, self).__init__()
        print('Child')
    def bar(self, message):
        super(FooChild, self).bar(message)
        print('Child bar fuction')
        print(self.parent)
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

运行结果:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

实例2:
经典的菱形继承案例,BC 继承 A,然后 D 继承 BC,创造一个 D 的对象。

     ---> B ---
A --|          |--> D
     ---> C ---

使用 super() 可以很好地避免构造函数被调用两次。

class A():
    def __init__(self):
        print('enter A')
        print('leave A')
class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')
class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')
class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')
d = D()

运行结果:

enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D

实例3:
在学习 Python 类的时候,总会碰见书上的类中有 init() 这样一个函数,很多同学百思不得其解,其实它就是 Python 的构造方法。
构造方法类似于类似 init() 这种初始化方法,来初始化新创建对象的状态,在一个对象呗创建以后会立即调用,比如像实例化一个类:

f = FooBar()
f.init()

使用构造方法就能让它简化成如下形式:

f = FooBar()

你可能还没理解到底什么是构造方法,什么是初始化,下面我们再来举个例子:

class FooBar:
    def __init__(self):
        self.somevar = 42
>>>f = FooBar()
>>>f.somevar

我们会发现在初始化 FooBar 中的 somevar 的值为 42 之后,实例化直接就能够调用 somevar 的值;如果说你没有用构造方法初始化值得话,就不能够调用,明白了吗?
在明白了构造方法之后,我们来点进阶的问题,那就是构造方法中的初始值无法继承的问题。
例子:

class Bird:
    def __init__(self):
          self.hungry = True
    def eat(self):
          if self.hungry:
               print 'Ahahahah'
          else:
               print 'No thanks!'
class SongBird(Bird):
     def __init__(self):
          self.sound = 'Squawk'
     def sing(self):
          print self.song()
sb = SongBird()
sb.sing()    # 能正常输出
sb.eat()     # 报错,因为 songgird 中没有 hungry 特性

那解决这个问题的办法有两种:
1、调用未绑定的超类构造方法(多用于旧版 python 阵营)

class SongBird(Bird):
     def __init__(self):
          Bird.__init__(self)
          self.sound = 'Squawk'
     def sing(self):
          print self.song()

原理:在调用了一个实例的方法时,该方法的self参数会自动绑定到实例上(称为绑定方法);如果直接调用类的方法(比如Bird.init),那么就没有实例会被绑定,可以自由提供需要的self参数(未绑定方法)。
2、使用super函数(只在新式类中有用)

class SongBird(Bird):
     def __init__(self):
          super(SongBird,self).__init__()
          self.sound = 'Squawk'
     def sing(self):
          print self.song()

原理:它会查找所有的超类,以及超类的超类,直到找到所需的特性为止。

65、tuple()

a)描述

tuple 函数将可迭代系列(如列表)转换为元组。

b)语法

tuple 的语法:tuple( iterable )

c)参数

iterable:要转换为元组的可迭代序列。

d)返回值

返回元组。

e)实例

实例1:

list1= ['Google', 'Taobao', 'Kevin', 'Baidu']
tuple1=tuple(list1)
print("tuple1:",tuple1)

运行结果:

tuple1: ('Google', 'Taobao', 'Kevin', 'Baidu')

实例2(tuple() 可以将字符串,列表,字典,集合转化为元组):

a = 'www'
b = tuple(a)
print("b:",b)
c = {'www':123,'aaa':234}
d = tuple(c)
print("d:",d)
e = set('abcd')
print("e:",e)
f = tuple(e)
print("f:",f)

运行结果:

b: ('w', 'w', 'w')
d: ('www', 'aaa')        # 将字段转换为元组时,只保留键!
e: {'a', 'b', 'd', 'c'}
f: ('a', 'b', 'd', 'c')

66、type()

type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

b)语法

type() 方法的语法:
type(object)
type(name, bases, dict)

c)参数

name:类的名称。
bases:基类的元组。
dict:字典,类内定义的命名空间变量。

d)返回值

一个参数返回对象类型, 三个参数,返回新的类型对象。

e)实例

实例1:

# 一个参数实例
print("type(1):",type(1))
print("type('kevin'):",type('kevin'))
print("type([2]):",type([2]))
print("type({0: 'zero'}):",type({0: 'zero'}))
x = 1
print("type(x) == int:",type(x) == int)  # 判断类型是否相等
# 三个参数
class X(object):
    a = 1
X = type('X', (object,), dict(a=1))  # 产生一个新的类型 X
print("X:",X)

运行结果:

type(1): 
type('kevin'): 
type([2]): 
type({0: 'zero'}): 
type(x) == int: True
X: 

实例2:

class A:
    pass
class B(A):
    pass
print("isinstance(A(), A):",isinstance(A(), A))
print("type(A()) == A:",type(A()) == A)
print("isinstance(B(), A):",isinstance(B(), A))
print("type(B()) == A:",type(B()) == A)

运行结果:

isinstance(A(), A): True
type(A()) == A: True
isinstance(B(), A): True
type(B()) == A: False

67、vars()

a)描述

原文:
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
中文:
vars([object]) -> dictionary
没有参数,等价于locals()。
等价于object.__dict__
诠释:
vars() 函数返回对象object的属性和属性值的字典对象。

b)语法

vars() 函数语法:vars([object])

c)参数

object:对象。

d)返回值

返回对象object的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值 类似 locals()。

e)实例
print(vars())
class Kevin:
    a = 1
print(vars(Kevin))
kevin = Kevin()
print(vars(kevin))

运行结果:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000022F9DE10970>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'D:/Python_Project/Temp.py', '__cached__': None}
{'__module__': '__main__', 'a': 1, '__dict__': , '__weakref__': , '__doc__': None}
{}

68、zip()

a)描述

原文:
zip(iterables) --> zip object
Return a zip object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__() method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration.
中文:
zip(
iterables) --> zip object
返回一个zip对象,其.__next__()方法返回一个元组,其中第i个元素来自第i个迭代参数。.__next__()方法将继续执行,直到参数序列中最短的迭代被用尽,然后它将引发StopIteration。
诠释:
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

b)语法

zip 语法:zip([iterable, ...])

c)参数

iterabl -- 一个或多个迭代器。

d)返回值

返回一个对象。

e)实例
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b)  # 返回一个对象
print("zipped:",zipped)
print("list(zipped):",list(zipped))  # list() 转换为列表
print("list(zip(a, c)):",list(zip(a, c)))  # 元素个数与最短的列表一致
a1, a2 = zip(*zip(a, b))  # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
print("list(a1):",list(a1))
print("list(a2):",list(a2))

运行结果:

zipped: 
list(zipped): [(1, 4), (2, 5), (3, 6)]
list(zip(a, c)): [(1, 4), (2, 5), (3, 6)]
list(a1): [1, 2, 3]
list(a2): [4, 5, 6]

69、__import__()

a)描述

原文:
__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. The level argument 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.
中文:
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
导入一个模块。因为这个函数是供Python解释器使用的,而不是通用的,所以最好使用importlib.import_module()以编程方式导入模块。
全局变量仅用于确定上下文;它们没有被修改。当地人的争论是没有用的。fromlist应该是一个要模拟from name import…的名称列表。或一个空列表来模拟import name
当从包中导入模块时,请注意以下几点:__import__('A.B', ...),当fromlist为空时返回包A,当fromlist不为空时返回子模块B。level参数用于确定是执行绝对导入还是相对导入:0是绝对导入,而正数是相对于当前模块要搜索的父目录的数量。
诠释:
__import__() 函数用于动态加载类和函数 。
如果一个模块经常变化就可以使用 __import__() 来动态载入。

b)语法

__import__ 语法:__import__(name[, globals[, locals[, fromlist[, level]]]])

c)参数

name:模块名

d)返回值

返回元组列表。

e)实例

a.py 文件代码:

import os  
print ('在 a.py 文件中 %s' % id(os))

test.py 文件代码:

import sys  
__import__('a')        # 导入 a.py 模块

运行结果:
执行test.py文件

在 a.py 文件中 2655185398576

你可能感兴趣的:(Python内置函数(7))