Python 内置函数二

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shelbaydo/article/details/84727073

Python sum() 函数

sum() 方法对系列进行求和计算。
以下展示了使用 sum 函数的实例:

>>>sum([0,1,2])  
3  
>>> sum((2, 3, 4), 1)        # 元组计算总和后再加 1
10
>>> sum([0,1,2,3,4], 2)      # 列表计算总和后再加 2
12

Python basestring() 函数

basestring() 方法是 str 和 unicode 的超类(父类),也是抽象类,因此不能被调用和实例化,但可以被用来判断一个对象是否为 str 或者 unicode 的实例,isinstance(obj, basestring) 等价于 isinstance(obj, (str, unicode))。

以下展示了使用 basestring 函数的实例:

>>>isinstance("Hello world", str)
True
>>> isinstance("Hello world", basestring)
True

Python execfile() 函数

execfile() 函数可以用来执行一个文件。

以下是 execfile() 方法的语法:

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

参数

  • filename – 文件名。
  • globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
  • locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
    以下展示了使用 execfile 函数的实例:
    假设文件 hello.py,内容如下:
print('runoob');

execfile 调用该文件

 >>>execfile('hello.py')
runoob

Python issubclass() 函数

issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。
如果 class 是 classinfo 的子类返回 True,否则返回 False。

以下展示了使用 issubclass 函数的实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A:
    pass
class B(A):
    pass
    
print(issubclass(B,A))    # 返回 True

Python super() 函数

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

以下展示了使用 super 函数的实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
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),然后把类B的对象 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.

Python bin() 函数

bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
以下展示了使用 bin 函数的实例:


>>>bin(10)
'0b1010'
>>> bin(20)
'0b10100'

Python file() 函数

file() 函数用于创建一个 file 对象,它有一个别名叫 open(),更形象一些,它们是内置函数。参数是以字符串的形式传递的。
测试文件 test.txt,内容如下:

RUNOOB1
RUNOOB2

>>>f = file('test.txt')
>>> f.read()
'RUNOOB1\nRUNOOB2\n'

Python iter() 函数

iter() 函数用来生成迭代器。
返回值
迭代器对象。

>>>lst = [1, 2, 3]
>>> for i in iter(lst):
...     print(i)
... 
1
2
3

Python property() 函数

定义一个可控属性值 x

class C(object):
    def __init__(self):
        self._x = None
 
    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.")

如果 c 是 C 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。
如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。
将 property 函数用作装饰器可以很方便的创建只读属性:

class Parrot(object):
    def __init__(self):
        self._voltage = 100000
 
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

上面的代码将 voltage() 方法转化成同名只读属性的 getter 方法。
property 的 getter,setter 和 deleter 方法同样可以用作装饰器:

class C(object):
    def __init__(self):
        self._x = None
 
    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x
 
    @x.setter
    def x(self, value):
        self._x = value
 
    @x.deleter
    def x(self):
        del self._x

Python Tuple(元组) tuple()方法

Python 元组 tuple() 函数将列表转换为元组。

以下实例展示了 tuple()函数的使用方法:

>>>tuple([1,2,3,4])
 
(1, 2, 3, 4)
 
>>> tuple({1:2,3:4})    #针对字典 会返回字典的key组成的tuple
 
(1, 3)
 
>>> tuple((1,2,3,4))    #元组会返回元组自身
 
(1, 2, 3, 4)

Python bool() 函数

bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。
bool 是 int 的子类。

以下展示了使用 bool 函数的实例:

>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(2)
True
>>> issubclass(bool, int)  # bool 是 int 子类

Python filter() 函数

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

以下展示了使用 filter 函数的实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

输出结果 :

[1, 3, 5, 7, 9]

猜你喜欢

转载自blog.csdn.net/shelbaydo/article/details/84727073
今日推荐