Python内建函数(D)

来源:互联网 发布:淘宝封店重开技术 编辑:程序博客网 时间:2024/06/06 00:56
  •  dir([object])

说明:不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

参数object: 对象、变量、类型。

示例:

复制代码
>>> dir()['__builtins__', '__doc__', '__name__', '__package__']>>> import struct>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'struct']>>> dir(struct)['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']>>> class Person(object):...     def __dir__(self):...             return ["name", "age", "country"]...>>> dir(Person)['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']>>> tom = Person()>>> dir(tom)['age', 'country', 'name']
复制代码

 

  • delattr(object, name)

说明:删除object对象名为name的属性。

参数object:对象。

参数name:属性名称字符串。

示例:

复制代码
>>> class Person:...     def __init__(self, name, age):...             self.name = name...             self.age = age...>>> tom = Person("Tom", 35)>>> dir(tom)['__doc__', '__init__', '__module__', 'age', 'name']>>> delattr(tom, "age")>>> dir(tom)['__doc__', '__init__', '__module__', 'name']
复制代码

 

  • dict([arg])

说明:创建数据字典。

示例:

复制代码
>>> a = dict() #空字典>>> a{}>>> b = dict(one = 1, two = 2)>>> b{'two': 2, 'one': 1}>>> c = dict({'one':1, 'two':2})>>> c{'two': 2, 'one': 1}>>> d= dict([['two', 2], ['one', 1]])>>> d{'two': 2, 'one': 1}>>> e ={'two': 2, 'one': 1}>>> e{'two': 2, 'one': 1}
复制代码

 

  • divmod(a, b)

说明:返回一个数据对,等价于( a // b, a % b)

参数abintlongfloat

示例:

复制代码
>>> divmod(5,3)(1, 2)>>> divmod(5.5, 2.2)(2.0, 1.0999999999999996)>>> divmod(5.5, 2)(2.0, 1.5)
复制代码
原创粉丝点击