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
    
     
  • 相关阅读:
    在命令行下运行Matlab
    VMWare无法共享文件夹(Win7宿主机Ubuntu14.04客户机)
    [转] CVonline: Image Databases
    第二天
    第一天
    二宝软件的NABCD分析
    用c++实现环形数组的最大子数组之和
    返回一个二维整数数组中最大子数组的和
    求最大子数组之和
    四则运算
  • 原文地址:https://www.cnblogs.com/FinnChan/p/11976752.html
Copyright © 2011-2022 走看看