📜  方法获取名字python(1)

📅  最后修改于: 2023-12-03 14:55:05.006000             🧑  作者: Mango

方法获取名字Python

在Python中,获取名字和变量绑定的值是非常重要的。Python提供了很多方法来获取程序中的名字,其中包括变量、函数、模块等。在本文中,我们将探讨一些获取名字的方法。

1. 使用type函数获取变量名
x = 5
print(type(x).__name__)

Output:

"int"

该方法通过使用内置函数之一type方法来获取变量类型的名称。但是,由于Python中的类型是动态的,因此需要使用__name__属性获取类型名称。

2. 使用locals()和globals()函数获取所有变量名
x = 5
y = 10

print("Global variables: ")
print(globals().keys())

print("Local variables: ")
print(locals().keys())

Output:

Global variables: dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'x', 'y'])
Local variables: dict_keys(['x', 'y'])

此方法可用于获取程序中定义的所有全局和局部变量的名称。但是请注意,它们将返回字典对象的视图,因此需要使用keys()方法获取名称列表。

3. 使用dir()函数获取对象的属性
a = "Hello, World!"
print(dir(a))

Output:

['__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', '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']

dir()函数返回对象的属性或方法名称列表。对于字符串,它会返回所有内置的字符串方法,以及所有Python为该对象提供的内置方法。这对于确定可调用的方法非常有用,在获取自定义对象的属性信息时也很有用,例如获取自定义类的所有属性。

4. 使用inspect模块获取对象信息
import inspect

def func():
    a = 1
    b = "2"
    return

print(inspect.getmembers(func))

Output:

[('__class__', <class 'function'>), ('__delattr__', <method-wrapper '__delattr__' of function object at 0x7fc3b68ff550>),
 ('__dir__', <built-in method __dir__ of function object at 0x7fc3b68ff550>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of function object at 0x7fc3b68ff550>), ('__format__', <built-in method __format__ of function object at 0x7fc3b68ff550>),
 ('__ge__', <method-wrapper '__ge__' of function object at 0x7fc3b68ff550>), ('__get__', <method-wrapper '__get__' of function object at 0x7fc3b68ff550>), ('__getattribute__', <method-wrapper '__getattribute__' of function object at 0x7fc3b68ff550>), ('__globals__', {...}), ('__gt__', <method-wrapper '__gt__' of function object at 0x7fc3b68ff550>), ('__hash__', <method-wrapper '__hash__' of function object at 0x7fc3b68ff550>), ('__init__', <method-wrapper '__init__' of function object at 0x7fc3b68ff550>), 
 ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x563a94894760>), ('__kwdefaults__', None), ('__le__', <method-wrapper '__le__' of function object at 0x7fc3b68ff550>), ('__lt__', <method-wrapper '__lt__' of function object at 0x7fc3b68ff550>), ('__module__', '__main__'), ('__name__', 'func'), ('__ne__', <method-wrapper '__ne__' of function object at 0x7fc3b68ff550>), 
 ('__new__', <built-in method __new__ of type object at 0x563a93d883b0>), ('__qualname__', 'func'), 
 ('__reduce__', <built-in method __reduce__ of function object at 0x7fc3b68ff550>), 
 ('__reduce_ex__', <built-in method __reduce_ex__ of function object at 0x7fc3b68ff550>), ('__repr__', <method-wrapper '__repr__' of function object at 0x7fc3b68ff550>), ('__setattr__', <method-wrapper '__setattr__' of function object at 0x7fc3b68ff550>), ('__sizeof__', 136), ('__str__', <method-wrapper '__str__' of function object at 0x7fc3b68ff550>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x563a94894760>), ('__weakref__', None), ('a', 1), ('b', '2')] 

inspect模块利用强大的反射工具,可以检查对象的源代码、获取对象的方法、属性、参数等。getmembers()函数返回一个通过元组列表来描述对象所提供的所有成员的列表。