Python内置函数(51-60)

版权声明:本文为博主原创文章,未经博主允许不得转载。不准各种形式的复制及盗图 https://blog.csdn.net/qq_26816591/article/details/88557846
# 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() 根据指定函数,对序列进行映射

猜你喜欢

转载自blog.csdn.net/qq_26816591/article/details/88557846