python in 详解_Python核心模块详解解之__builtin__模块

__builtin__模块包含Python的内建函数,如apple函数,它可以以不同方式调用函数,包括传递元组和字典参数。此外,讨论了import模块、reload模块的功能,以及dir()、vars()和type()等实用函数的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、__builtin__模块

__builtin__包含了Python许多内建的函数,你不必手动导入此模块,就可直接调用许多内建的函数.

1.1函数apple(object[,args[,kwargs]])

1.1.1 apple函数可以调用一个函数,函数的参数从元组中获取.

Example 1-1. Using the apply

Function

#Fileanme:

builtin-apply-example-1.py

def function(a, b):

print a,

b

apply(function, ("whither", "canada?"))

apply(function, (1, 2 + 3))

1.1.2 apple函数可以调用一个函数,函数的关键参数从字典中获取.

Example 1-2.

使用apple函数传递关键参数

#Filename:

builtin-apply-example-2.py

def function(a, b):

print a,

b

apply(function, ("crunchy", "frog"))

apply(function, ("crunchy",), {"b": "frog"})

apply(function, (), {"a": "crunchy", "b": "frog"})

1.1.3 apple函数最普通的用法是:把派生类的构造函数的参数传递给基娄的构造函数,特别当构造函数有大量参数时,这个用法是相当有用的.

Example 1-3. Using the apply

Function to Call Base Class Constructors

#Filename:

builtin-apply-example-3.py

class Rectangle:

def _ _init_

_(self, color="white", width=10, height=10):

print "create a", color, self, "sized", width, "x", height

class RoundedRectangle(Rectangle):

def _ _init_

_(self, **kw):

apply(Rectangle._ _init_ _, (self,), kw)

rect = Rectangle(color="green", height=100, width=100)

rect = RoundedRectangle(color="blue", height=20)

1.1.4 Python2.0以后提供了一条替代apple函数的预备语法.直接调使用一个简单的函数,参数加*标识元组,参数加**标识字典.

下面二个语法是等效的:

result = function(*args,

**kwargs)

result = apply(function, args, kwargs)

1.2 载入(import)模块和生载(reload)模块

如果你想要直接导入模块到你的程序中(避免在每次使用时导入模块.),那么你可以使用import

...语句。例如:你想导入模块math中的sqrt,则使用from math import

sqrt,如果你想要输入所有math模块使用的名字,那么你可以使用import sys或from sys import

*进行导入,但要注意尽量用import ...,这样的语句可以使用你的程序更直观.

1.3 dir()函数

dir()函数以列表形式返回一个特定的模块,类,对象或它类型的所有成员.

Example 1-4. Using the dir Function

to Find All Members of a Class

#Filename:

builtin-dir-example-2.py

class A:

def

a(self):

pass

def

b(self):

pass

class B(A):

def

c(self):

pass

def

d(self):

pass

dir(A)

dir(B)

dir(IOError)

1.4 vars()函数.

vars()函数以字典形式返回每个成员的当前值,如果vars函数没有带参数,那么它会返回包含当前局部命名空间中所有成员的当前值的一个字典.

Example 1-5. Using the vars Function

File: builtin-vars-example-1.py

book = "library2"

pages = 250

scripts = 350

print "the %(book)s book contains more than %(scripts)s scripts" %

vars()

输出:the library book contains more than 350 scripts

1.5 type()函数.

1.5.1

type()函数可以检查任何变量的类型.

Example 1-6. Using the type Function

File: builtin-type-example-1.py

def dump(value):

print

type(value), value

dump(1)

dump(1.0)

dump("one")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值