Python3內置函數(51-60)

# 51.delattr()
# 用於刪除屬性。
class A(object):
    x = 12
    y = 23


delattr(A, 'x')

# 52.format()
# Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
# 基本語法是通過 {} 和 : 來代替以前的 % 。
# format 函數可以接受不限個參數,位置可以不按順序。
print("{},{}".format('A', 'B'))  # 不指定位置,按照默認順序
print("{0},{1}".format('A', 'B'))  # 指定位置
print("{0},{1},{0}".format('A', 'B'))  # 指定位置
print("Name:{name}, Age:{age}".format(name="Joe.Smith", age="18"))  # 變量賦值
dict1 = {'name': 'Joe.Smith', 'age': '18'}
print('姓名:{name},年齡:{age}'.format(**dict1))  # 字典賦值(鍵名=變量名)
lst1 = ['Joe.Smith', '18']
print('姓名:{0[0]},年齡:{0[1]}'.format(lst1))  # 列表賦值 注意變量前一定得有0
num1 = 18
print('年齡:{}'.format(num1))

# 53.frozenset()
# 返回一個凍結的集合,凍結後集合不能再添加或刪除任何元素。
set1 = range(10)
frozenset(set1)
for i in set1:
    print(i, end=' ')
print()


# 54.getattr()
# 用於返回一個對象屬性值。
class B(object):
    num2 = 18


print(getattr(B, 'num2'))

# 55.globals()
# 會以字典類型返回當前位置的全部全局變量。
str1 = 'hello'
print(globals())


# 56.hasattr()
# 用於判斷對象是否包含對應的屬性。
# hasattr(object, name)
# object -- 對象。
# name -- 字符串,屬性名。
class C(object):
    num2 = 18


print(hasattr(C, 'num3'))

# 57.hash()
# 用於獲取取一個對象(字符串或者數值等)的哈希值。
num2 = 18
str2 = '18'
print(hash(num2))
print(hash(str2))

# 58.list()
# 用於將元組或字符串轉換爲列表。
# 元組與列表是非常類似的,區別在於元組的元素值不能修改,元組是放在括號中(),列表是放於方括號中[]。
tuple1 = (1, 2, 3, 45, 6, 43, 2, 343, 53)
print(list(tuple1))

# 59.locals()
# 會以字典類型返回當前位置的全部局部變量。
print(locals())

# 60.map()
# 會根據提供的函數對指定序列做映射。
# 第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表。
# map(function, iterable, ...)
# function -- 函數
# iterable -- 一個或多個序列

lst2 = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
lst2 = list(lst2)
print(lst2)

要點:

  • delattr() 刪除某個屬性
  • format() 格式化輸出,注意指定位置與不指定位置,字典賦值與列表賦值
  • frozenset() 凍結一個集合,該集合不能添加或刪除元素
  • getattr() 返回對象的某個屬性值
  • globals() 以字典輸出當前位置的所有全局變量
  • hasattr() 判斷對象是否包含某個屬性
  • hash() 獲取對象的哈希值
  • list() 將元組或字符串轉換爲列表
  • locals() 以字典返回當前位置的所有局部變量
  • map() 根據指定函數,對序列進行映射

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章