zoukankan      html  css  js  c++  java
  • python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr

    一、type()函数

    判断基本数据类型可以直接写intstr等:

     1 >>> class Animal(object):
     2 ...     pass
     3 ... 
     4 >>> type(123)
     5 <class 'int'>
     6 >>> type('123')
     7 <class 'str'>
     8 >>> type(None)
     9 <class 'NoneType'>
    10 >>> type(abs)
    11 <class 'builtin_function_or_method'>
    12 >>> type(Animal())
    13 <class '__main__.Animal'>
    1 >>> type(123) == type(456)
    2 True
    3 >>> type(123) == int
    4 True

    判断一个对象是否是函数:

     1 >>> import types
     2 >>> def fn():
     3 ...     pass
     4 ...
     5 >>> type(fn)==types.FunctionType
     6 True
     7 >>> type(abs)==types.BuiltinFunctionType
     8 True
     9 >>> type(lambda x: x)==types.LambdaType
    10 True
    11 >>> type((x for x in range(10)))==types.GeneratorType
    12 True

    二、isinstance()函数

    对于class的继承关系来说,使用type()就很不方便。如果要判断class的类型,可以使用isinstance()函数。

     1 >>> class Animal(object):
     2 ...     pass
     3 ... 
     4 >>> class Dog(Animal):
     5 ...     pass
     6 ... 
     7 >>> d = Dog()
     8 >>> isinstance(d, Dog)
     9 True
    10 >>> isinstance(d, Animal)
    11 True

    用isinstance()判断基本类型:

    1 >>> isinstance('a', str)
    2 True
    3 >>> isinstance(123, int)
    4 True
    5 >>> isinstance(b'a', bytes)
    6 True

    并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:

    1 >>> isinstance([1, 2, 3], (list, tuple))
    2 True
    3 >>> isinstance((1, 2, 3), (list, tuple))
    4 True

    优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。

    三、dir()函数

    如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

    >>> dir('abc')
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__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']

    列表中类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

    1 >>> len('abc')
    2 3
    3 >>> 'abc'.__len__()
    4 3

    自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:

    1 >>> class MyDog(object):
    2 ...     def __len__(self):
    3 ...         return 100
    4 ... 
    5 >>> dog = MyDog()
    6 >>> len(dog)
    7 100

    列表中剩下的都是普通属性或方法,比如lower()返回小写的字符串:

    1 >>> 'abc'.upper()
    2 'ABC'

    四、getattr()setattr()以及hasattr()

    测试该对象的属性:

     1 >>> class MyObject(object):
     2 ...     def __init__(self):
     3 ...         self.x = 9
     4 ...     def power(self):
     5 ...         return self.x * self.x
     6 ... 
     7 >>> obj = MyObject()
     8 >>> hasattr(obj, 'x')
     9 True
    10 >>> hasattr(obj, 'y')
    11 False
    12 >>> 
    13 >>> setattr(obj, 'y', 20)
    14 >>> hasattr(obj, 'y')
    15 True
    16 >>> getattr(obj, 'y')
    17 20
    18 >>> getattr(obj, 'z')
    19 Traceback (most recent call last):
    20   File "<stdin>", line 1, in <module>
    21 AttributeError: 'MyObject' object has no attribute 'z'
    22 >>> getattr(obj, 'z', 100)    # 指定默认值
    23 100

    测试该对象的方法:

    1 >>> hasattr(obj, 'power')
    2 True
    3 >>> getattr(obj, 'power')
    4 <bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
    5 >>> fn = getattr(obj, 'power')
    6 >>> fn
    7 <bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
    8 >>> fn()
    9 81
  • 相关阅读:
    我眼中的DevOps
    Jenkins常用插件介绍之权限控制插件Role-based Authorization Strategy
    sql查询一个班级中总共有多少人以及男女分别多少人
    win8 图片等路径
    WPF 设置TextBox为空时,背景为文字提示。
    WCF服务发布
    win8 摄像
    oracle 删除主键
    oracle 数据库连接
    oracle 创建用户表
  • 原文地址:https://www.cnblogs.com/gundan/p/8052399.html
Copyright © 2011-2022 走看看