zoukankan      html  css  js  c++  java
  • type() & dir()

    type( )

    >>> import types
    >>> def fn():
    ...     pass
    ...
    >>> type(fn)==types.FunctionType
    True
    >>> type(abs)==types.BuiltinFunctionType
    True
    >>> type(lambda x: x)==types.LambdaType
    True
    >>> type((x for x in range(10)))==types.GeneratorType
    True

    dir()
    
    >>> hasattr(obj, 'x') # 有属性'x'吗?
    True
    >>> obj.x
    9
    >>> hasattr(obj, 'y') # 有属性'y'吗?
    False
    >>> setattr(obj, 'y', 19) # 设置一个属性'y'
    >>> hasattr(obj, 'y') # 有属性'y'吗?
    True
    >>> getattr(obj, 'y') # 获取属性'y'
    19
    >>> obj.y # 获取属性'y'
    19
    

    如果试图获取不存在的属性,会抛出AttributeError的错误:

    >>> getattr(obj, 'z') # 获取属性'z'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'MyObject' object has no attribute 'z'
    

    可以传入一个default参数,如果属性不存在,就返回默认值:

    >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404
    404
    

    也可以获得对象的方法:

    >>> hasattr(obj, 'power') # 有属性'power'吗?
    True
    >>> getattr(obj, 'power') # 获取属性'power'
    <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
    >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
    >>> fn # fn指向obj.power
    <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
    >>> fn() # 调用fn()与调用obj.power()是一样的
    81
    
     
  • 相关阅读:
    SpringBoot集成RocketMQ报错:Bad annotation definition in @ExtRocketMQTemplateConfiguration...
    RocketMQ分析
    SpringBoot 自定义 health Actuator 原理
    【质量】容错机制
    【Java】ByteBuffer介绍
    【AWS】Essentials
    【QA123】NFR 非功能性需求
    【JVM123】OOM分析和解决
    【网络123】Http返回码
    【网络123】HTTP连接
  • 原文地址:https://www.cnblogs.com/FinnChan/p/11976752.html
Copyright © 2011-2022 走看看