Python dir()方法–列出对象属性

python编程语言是一种基于对象的编程语言,其中每个变量、值等都是一个对象。对象包含不同的属性,这些属性与对象类型不同。为了列出和显示对象属性,Python提供 目录() 方法,该方法将以列表形式返回所有属性名称。dir()方法是默认提供的内置方法,不需要安装或导入额外的模块。

null

dir()方法语法

dir()方法具有以下语法,其中is接受单个参数。

dir(OBJECT)
  • 对象是一个变量、值、类等,这些属性将被返回。此参数是可选的。

dir()方法返回给定对象属性名的列表。

用dir()列出对象属性

在下面的示例中,我们将列出不同对象类型的属性,如list、string、class definition和class instance。

numbers = [1,2,3]sentence = "I like pythontect.com"class Person:   name = "İsmail Baydan"print("List attributes:",dir(numbers))print("String attributes:",dir(sentence))print("Class attributes:",dir(Person))p = Person()print("Class instance attributes:",dir(p))

输出如下。

List attributes:['add', 'class', 'contains', 'delattr', 'delitem', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'gt', 'hash', 'iadd', 'imul', 'init', 'init_subclass', 'iter', 'le', 'len', 'lt', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'reversed', 'rmul', 'setattr', 'setitem', 'sizeof', 'str', 'subclasshook', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']String attributes:['add', 'class', 'contains', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str', 'subclasshook', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']Class attributes:['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'name']Class instance attributes:['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'name']

当前本地作用域中的名称列表

dir()方法的对象参数是可选的。如果dir()方法中没有提供任何对象参数,则返回当前本地作用域中的名称列表,如下所示。这将包括导入的模块、变量、函数、列表、类等。

dir()

输出如下。

['Person', 'annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec', 'a', 'age', 'count', 'errmessage', 'i', 'items', 'multiplY', 'multiply', 'numbers', 'os', 'p', 'print_err', 'result', 'say_hello', 'sentence', 'sentence_list', 'sys']
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享