获取对象的值

获取对象的类型:

>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>>
复制代码

以上是通过type()这个函数来获取123,str,None的对象类型

判断两个类型是否相同:

>>> type(123)==type(456)
True
>>> type('str')== str
True
>>> type('abc')== type('def')
True
>>> type(123) == int
True
>>> type(123) == type('abc')
False
复制代码

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

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

使用isinstance() 进行判断类型:

>>> class Animal(object):
...     def run():
...             print('running...')
...
>>> class Dog(Animal):
...     def run():
...             pass
...
>>> a = Animal()
>>> d = Dog()
>>> isinstance(d, Dog)
True
复制代码

我们看看子类的对象和父类的关系:

>>> isinstance(d, Dog) and isinstance(d, Animal)
True
复制代码

前面我们说过,子类的对象也是属于父类类型,所以上面返回是true

type 判断类型跟isinstance是一样的:

>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'c', bytes)
True
>>>
复制代码

使用dir()获取一个对象的所有方法和属性:

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

总结:

1、通过type()判断对象类型
2、还可以通过isinstance() 判断对象类型
3、通过dir()获取对象的方法和属性
复制代码

ps:程序员要注意健康,健康知识: 鼻子不通气很难受,可以看看这个链接:https://zhidao.baidu.com/question/135383907.html 我正在尝试揉搓和洗鼻方式,看看效果~。

转载于:https://juejin.im/post/5ad76809f265da502f735cff

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值