python反射之访问元数据(一)

172 阅读4分钟

如前文所示,当你对一个自定义对象使用dir()方法时,返回的结果中有很多不是人为定义的一些属性。这些属性一般保存了对象的元数据,支持修改,但是绝大多数情况下不需要取改动他们,以免发生意外的错误。

1 确定对象类型

在types模块中定义了python所有的内置类型,结合内置方法isinstance()方法就可以确定对象的类型了。

a = 12
print(isinstance(a, int))

result:

True

2 模块相关的属性

模块相关的属性如下表所示

属性说明
doc文档字符串,若没有则为None
name定义时的模块名,不会因起别名而改变
dict是一个包含可用属性名、可用属性构成的字典
file该模块的文件路径,内建的模块没有该属性,访问会报错

示例如下:

import random as ma
​
print(ma.__doc__)

result:

Random variable generators.
integers
--------
       uniform within range
​
sequences
---------
       pick random element
       pick random sample
       pick weighted random sample
       generate random permutation
​
distributions on the real line:
------------------------------
       uniform
       triangular
       normal (Gaussian)
       lognormal
       negative exponential
       gamma
       beta
       pareto
       Weibull
​
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
       circular uniform
       von Mises
General notes on the underlying Mersenne Twister core generator:
​
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
  and is, therefore, threadsafe.
print(ma.__name__)

result:

random
print(ma.__dict__)

result:

{'__name__': 'random', '__doc__': 'Random variable generators.\n\n    integers\n    --------\n           uniform within range\n\n    sequences\n    ---------\n           pick random element\n           pick random sample\n           pick weighted random sample\n           generate random permutation\n\n    distributions on the real line:\n    ------------------------------\n           uniform\n           triangular\n           normal (Gaussian)\n           lognormal\n           negative exponential\n           gamma\n           beta\n           pareto\n           Weibull\n\n    distributions on the circle (angles 0 to 2pi)\n    ---------------------------------------------\n           circular uniform\n           von Mises\n\nGeneral notes on the underlying Mersenne Twister core generator:\n\n* The period is 2**19937-1.\n* It is one of the most extensively tested generators in existence.\n* The random() method is implemented in C, executes in a single Python step,\n  and is, therefore, threadsafe.\n\n', '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000022DB8DE2748>, '__spec__': ModuleSpec(name='random', loader=<_frozen_importlib_external.SourceFileLoader object at 0x0000022DB8DE2748>, origin='D:\software\python\lib\random.py'), '__file__': 'D:\software\python\lib\random.py', '__cached__': 'D:\software\python\lib__pycache__\random.cpython-37.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2020 Python Software Foundation.
All Rights Reserved.
​
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
​
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
​
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}, '_warn': <built-in function warn>, '_MethodType': <class 'method'>, '_BuiltinMethodType': <class 'builtin_function_or_method'>, '_log': <built-in function log>, '_exp': <built-in function exp>, '_pi': 3.141592653589793, '_e': 2.718281828459045, '_ceil': <built-in function ceil>, '_sqrt': <built-in function sqrt>, '_acos': <built-in function acos>, '_cos': <built-in function cos>, '_sin': <built-in function sin>, '_urandom': <built-in function urandom>, '_Set': <class 'collections.abc.Set'>, '_Sequence': <class 'collections.abc.Sequence'>, '_sha512': <built-in function openssl_sha512>, '_itertools': <module 'itertools' (built-in)>, '_bisect': <module 'bisect' from 'D:\software\python\lib\bisect.py'>, '_os': <module 'os' from 'D:\software\python\lib\os.py'>, '__all__': ['Random', 'seed', 'random', 'uniform', 'randint', 'choice', 'sample', 'randrange', 'shuffle', 'normalvariate', 'lognormvariate', 'expovariate', 'vonmisesvariate', 'gammavariate', 'triangular', 'gauss', 'betavariate', 'paretovariate', 'weibullvariate', 'getstate', 'setstate', 'getrandbits', 'choices', 'SystemRandom'], 'NV_MAGICCONST': 1.7155277699214135, 'TWOPI': 6.283185307179586, 'LOG4': 1.3862943611198906, 'SG_MAGICCONST': 2.504077396776274, 'BPF': 53, 'RECIP_BPF': 1.1102230246251565e-16, '_random': <module '_random' (built-in)>, 'Random': <class 'random.Random'>, 'SystemRandom': <class 'random.SystemRandom'>, '_test_generator': <function _test_generator at 0x0000022DB8DE4048>, '_test': <function _test at 0x0000022DB8DF5D38>, '_inst': <random.Random object at 0x0000022DB8E190B8>, 'seed': <bound method Random.seed of <random.Random object at 0x0000022DB8E190B8>>, 'random': <built-in method random of Random object at 0x0000022DB8E190B8>, 'uniform': <bound method Random.uniform of <random.Random object at 0x0000022DB8E190B8>>, 'triangular': <bound method Random.triangular of <random.Random object at 0x0000022DB8E190B8>>, 'randint': <bound method Random.randint of <random.Random object at 0x0000022DB8E190B8>>, 'choice': <bound method Random.choice of <random.Random object at 0x0000022DB8E190B8>>, 'randrange': <bound method Random.randrange of <random.Random object at 0x0000022DB8E190B8>>, 'sample': <bound method Random.sample of <random.Random object at 0x0000022DB8E190B8>>, 'shuffle': <bound method Random.shuffle of <random.Random object at 0x0000022DB8E190B8>>, 'choices': <bound method Random.choices of <random.Random object at 0x0000022DB8E190B8>>, 'normalvariate': <bound method Random.normalvariate of <random.Random object at 0x0000022DB8E190B8>>, 'lognormvariate': <bound method Random.lognormvariate of <random.Random object at 0x0000022DB8E190B8>>, 'expovariate': <bound method Random.expovariate of <random.Random object at 0x0000022DB8E190B8>>, 'vonmisesvariate': <bound method Random.vonmisesvariate of <random.Random object at 0x0000022DB8E190B8>>, 'gammavariate': <bound method Random.gammavariate of <random.Random object at 0x0000022DB8E190B8>>, 'gauss': <bound method Random.gauss of <random.Random object at 0x0000022DB8E190B8>>, 'betavariate': <bound method Random.betavariate of <random.Random object at 0x0000022DB8E190B8>>, 'paretovariate': <bound method Random.paretovariate of <random.Random object at 0x0000022DB8E190B8>>, 'weibullvariate': <bound method Random.weibullvariate of <random.Random object at 0x0000022DB8E190B8>>, 'getstate': <bound method Random.getstate of <random.Random object at 0x0000022DB8E190B8>>, 'setstate': <bound  Random.setstate of <random.Random object at 0x0000022DB8E190B8>>, 'getrandbits': <built-in method getrandbits of Random object at 0x0000022DB8E190B8>}
print(ma.__file__)

result:

D:\software\python\lib\random.py

3 类相关的属性

类相关的属性如下表所示

属性说明
doc文档字符串,若没有则为None
name定义时的类名,不会因起别名而改变
dict是一个包含类里面可用属性名、可用属性构成的字典
module类所在模块的模块名,这里的结果是字符串形式的模块名,而不是模块对象
bases直接父类对象的元组,但只包含父类,更上层的类则不包含

示例如下:

class Person(object):
    """
    这是一个测试类
    """
​
    def __init__(self, name, age):
        self.name = name
        self.age = age
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
print(Person.__doc__)

result:

这是一个测试类
print(Person.__name__)

result:

Person
print(Person.__dict__)

result:

{'__module__': '__main__', '__doc__': '\n    这是一个测试类\n    ', '__init__': <function Person.__init__ at 0x000001E0112D9AF8>, 'say': <function Person.say at 0x000001E01130C048>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}
print(Person.__module__)

result:

__main__
print(Person.__bases__)

result:

(<class 'object'>,)

4 实例相关的属性

类相关的属性如下表所示

属性说明
dict是一个包含实例里面可用属性名、可用属性构成的字典
class实例的类对象

示例如下:

p = Person("小明", 23)
print(p.__dict__)

result:

{'name': '小明', 'age': 23}
print(p.__class__)

result:

<class '__main__.Person'>