设为首页 加入收藏

TOP

Python常用的内置函数(一)
2019-01-11 16:08:48 】 浏览:177
Tags:Python 常用 内置 函数

一  反射相关

  1 hasattr   根据字符串的形式 , 去判断对象中是否有成员

hasattr(object,name)
判断对象object是否包含名为name的特性(hasattr是通过调用getattr(object,name))是否抛出异常来实现的。
参数object:对象
参数name:特性名称
>>> hasattr(list, 'append')
True
>>> hasattr(list, 'add')
False
View Code

 

  2 getattr  根据字符串的形式,去对象中找成员.   第一个参数是(模块或对象或类),  第二个参数是(用户输入或值)

getattr(object, name [, defalut])
获取对象object名为name的特性,如果object不包含名为name的特性,将会抛出AttributeError异常;如果不包含名为name的特性
且提供default参数,将返回default。
参数object:对象
参数name:对象的特性名
参数default:缺省返回值
>>> class test():
...  name="ming"
...   def run(self):
...     return "Hello World"
...
>>> t=test()
>>> getattr(t, "name") #获取name属性,存在就打印出来。
'ming'
>>> getattr(t, "run") #获取run方法,存在就打印出方法的内存地址。
<bound method test.run of <__main__.test instance at 0x0269C878>>
>>> getattr(t, "run")() #获取run方法,后面加括号可以将这个方法运行。
'Hello World'
>>> getattr(t, "age") #获取一个不存在的属性。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age","18") #若属性不存在,返回一个默认值。
'18'
>>>
View Code

 

  3 setattr   根据字符串的形式 , 动态的设置一个成员(在内存中)  (三个参数, 第一个参数是要设置的变量, 第三个变量是要设置的值)

给对象的属性赋值,若属性不存在,先创建再赋值
>>> class test():
...     name="ming"
...     def run(self):
...             return "Hello World"
...
>>> t=test()
>>> hasattr(t, "age")   #判断属性是否存在
False
>>> setattr(t, "age", "18")   #为属相赋值,并没有返回值
>>> hasattr(t, "age")    #属性存在了
True
View Code

 

  4 delattr     

综合使用

>>> class test():
       name="ming"
       def run(self):
             return "Hello World">>> t=test()
>>> getattr(t, "age")    #age属性不存在
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'


>>> if getattr(t ,"age") is none: #当获取到这个age值为空时,需要给这个age重新赋值
    setattr(t,"age","18")
'True'

>>>getattr(t,"age")
'18'

 

 

 

二 基础数据类型相关

  1 bool     

  2 int

  3 float

  4 complex   复数   

complex(5,6)    

(5+6j)

  5 bin  整型转换为二进制

  6 oct  整型转换为八进制

  7 hex  整型转换为十六进制

  8 abs  求绝对值

  9 divmod  (除,余数)

  10 round     (值,小数后几位)

 ret =  round(4.563111347,3)    

 print(ret)

 4.563

 

  11 pow  幂运算

ret = pow(2,3)
print(ret)

8

 

  12 sum  

  13 max

  14 min

  15 list 

  16 tuple

  17 reversed  

       18  slice   和切片有关

  19 str

  20 format    

  21 bytes

  22 bytearry

  23 memoryview

  24 ord

  25 chr

  26 ascill

  27 repr

  28 dict

  29 set()

  30 frozenset

  31 len

  32 sorted

a = [1,3,5,-2,-4,-6]
b = sorted(a,key=abs)
print(a)
print(b)

  33 enumerate   

 a = enumerate()  返回一个元祖  a[0]序列号,a[1]数据

  34 all

接受一个迭代器,如果迭代器的所有元素都为真,那么返回True,否则返回False

>>> tmp_1 = ['python',123]
>>> all(tmp_1)
True
>>> tmp_2 = []
>>> all(tmp_2)
True
>>> tmp_3 = [0]
>>> all(tmp_3)
False

  35

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇OpenCV中图像的BGR格式及Img对象.. 下一篇如何对前端图片主题色进行提取?..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目