了解Python中vars()函數的功能及應用

Python 中的 vars() 函數

Python 中的 vars() 函數可以用於返回對象的屬性字典。它可以接受任何對象,包括模塊,函數,類,實例等,並返回對象的屬性字典。

舉個例子,我們可以使用 vars() 函數來查看模塊的屬性字典:

import math

print(vars(math))

輸出結果:

{'__name__': 'math', '__doc__': 'This module is always available.  It provides access to the
mathematical functions defined by the C standard.', '__package__': '', '__loader__': <_frozen_importlib_external.ExtensionFileLoader object at 0x7f9f3c7d9d30>, '__spec__': ModuleSpec(name='math', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x7f9f3c7d9d30>, origin='/usr/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so'), '__file__': '/usr/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so', '__cached__': '/tmp/pip-ephem-wheel-cache-jm6jzf1v/wheels/2d/c2/2f/a6f7a6b9f5a5d6d5e6d7c1f5f6c7f0d9a6b7a9f9f1b7a2b2f/math.cpython-38-x86_64-linux-gnu.so', 'acos': , 'acosh': , 'asin': , 'asinh': , 'atan': , 'atan2': , 'atanh': , 'ceil': , 'copysign': , 'cos': , 'cosh': , 'degrees': , 'e': 2.718281828459045, 'erf': , 'erfc': , 'exp': , 'expm1': , 'fabs': , 'factorial': , 'floor': , 'fmod': , 'frexp': , 'fsum': , 'gamma': , 'gcd': , 'hypot': , 'inf': inf, 'isclose': , 'isfinite': , 'isinf': , 'isnan': , 'ldexp': , 'lgamma': , 'log': , 'log10': , 'log1p': , 'log2': , 'modf': , 'nan': nan, 'pi': 3.141592653589793, 'pow': , 'radians': , 'sin': , 'sinh': , 'sqrt': , 'tan': , 'tanh': , 'tau': 6.283185307179586, 'trunc': }

另外,我們也可以使用 vars() 函數來查看對象的屬性字典:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person('John', 30)

print(vars(person))

輸出結果:

{'name': 'John', 'age': 30}

總之,Python 中的 vars() 函數可以用於返回對象的屬性字典,它可以接受任何對象,包括模塊,函數,類,實例等,並返回對象的屬性字典。

發佈留言