内置函数(BIF, built-in functions)是python内置对象类型之一,不需要额外导入任何模块即可直接使用,这些内置对象都封装在内置模块_builtins_之中,用C语言实现并且进行了大量优化,具有非常快的运行速度,推荐优先使用。
使用内置函数dir()函数可以查看所有内置函数和内置对象。
使用help()函数可以查看某个函数的用法。
内置函数共有68个,在这里,我挑一些经常使用需要大家熟练掌握的函数进行介绍,至于其他函数的用法可以参考这里的教程。点击这里,查看教程
In [1]: print(type(dir))
In [2]: def dosth():
...: print("dosth被调用")
...: print(type(dosth))
可以使用==来判断某个对象的类型是否是制定的类型。
对于基本的数据类型,可以使用其对应的类名。如果不是基本的数据类型,则需
要使用标准库types中定义的变量。
In [1]: print(type("123")==str)
True
In [2]: import types
In [3]: print(type(print)==types.BuiltinFunctionType)
True
In [4]: print(type(dosth)==types.FunctionType)
True
In [1]: class A(object):
...: pass
...: class B(A):
...: pass
...: class C(object):
...: pass
...: class D(object):
...: pass
...: print(issubclass(B,A))
True
In [2]: print(issubclass(B,(C,D)))
False
In [3]: print(issubclass(B,(A,C)))
True
In [1]: print(issubclass(bool,int))
True
In [2]: print(issubclass(bool,(int,str)))
True
In [1]: class A(object):
...: pass
...: class B(object):
...: pass
...: print(isinstance(A(),A))
True
In [2]: print(isinstance(A(),(A,B)))
True
In [1]: class A(object):
...: age = 18
...: def func(self):
...: print("func被调用")
...: a = A()
In [2]: print(hasattr(a,"age"))
True
In [3]: print(hasattr(a,"name"))
False
In [4]: print(hasattr(a,"func"))
True
In [5]: print(getattr(a,"age"))
18
In [6]: f = getattr(a,"func")
In [7]: f()
func被调用
In [8]: setattr(a,"name","mingming")
In [9]: print(getattr(a,"name"))
mingming
In [10]: delattr(a,"name")
In [11]: print(hasattr(a,"name"))
False
In [1]: str("hello,\nworld")
Out[1]: 'hello,\nworld'
In [2]: repr("hello,\nworld")
Out[2]: "'hello,\\nworld'"
In [3]: a = "hello"
In [4]: str(a)
Out[4]: 'hello'
In [5]: repr(a)
Out[5]: "'hello'"
In [6]: eval(repr(a)) == a
Out[6]: True
In [7]: eval(str(a)) == a
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 eval(str(a)) == a
in
NameError: name 'hello' is not defined
In [1]: callable(print)
Out[1]: True
In [2]: def do_sth():
...: pass
...:
In [3]: callable(do_sth)
Out[3]: True
In [4]: class MyClass(object):
...: def __call__(cls,*args,**kwargs):
...: print(args,kwargs)
...: mc = MyClass()
In [5]: callable(mc)
Out[5]: True