23、python面向对象编程--type()、isinstance()、dir()获取对象类型

1、type()

基本类型都可以用type()判断;

一个变量指向函数或者类,也可以用type()判断;

class Animal():
    pass

a = Animal()

'''基本类型都可以用`type()`判断'''
print('123的类型:', type(123))
print('"str"的类型:', type('str'))
print('123.67的类型:', type(123.67))
print('None的类型:', type(None))
'''一个变量指向函数或者类,也可以用`type()`判断'''
print('abs的类型:', type(abs))
print('a的类型:', type(a))

输出结果:
123的类型: <class 'int'>
"str"的类型: <class 'str'>
123.67的类型: <class 'float'>
None的类型: <class 'NoneType'>
abs的类型: <class 'builtin_function_or_method'>
a的类型: <class '__main__.Animal'>

type()函数返回的是对应的Class类型,在if语句中判断,就需要比较两个变量的type类型是否相同:

if type(123) == int:
    print('1')
    
输出
1

类似用法:
>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type('abc')==type('123')
True
>>> type('abc')==str
True
>>> type('abc')==type(123)
False

判断基本数据类型可以直接写intstr等,但如果要判断一个对象是否是函数可以使用types模块中定义的常量:

>>> 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

======================================================
import types
def Animal():
    pass
a = (type(Animal)==types.FunctionType)
print(a)

输出:
True

2、isinstance()

isinstance()判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上;

class Animal(object):
    pass


class Dog(Animal):
    pass

a = Animal()
b = Dog()

print(isinstance(a, Animal))
print(isinstance(b, Dog))
#isinstance()判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上
print(isinstance(b, Animal))

输出:
True
True
True

能用type()判断的基本类型也可以用isinstance()判断;

>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True

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

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

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

3、dir()

使用dir()函数获得一个对象的所有属性和方法,它返回一个包含字符串的list。

class Animal():
    def __init__(self):
        self.x = 9
    def run(self):
        pass

a = Animal()
#使用`dir()`函数获得一个对象的所有属性和方法,它返回一个包含字符串的list。
print(dir(a))

# 配合getattr()、setattr()以及hasattr(),可以直接操作一个对象的状态
print('a是否含有属性x:',hasattr(a,'x'))     # 有属性'x'吗?
print('a是否含有属性y:',hasattr(a,'y'))      # 有属性'y'吗?
setattr(a,'y',19)  # 设置属性'y'
print('a是否含有属性y:',getattr(a,'y'))   # 获取属性'y'

输出:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run', 'x']
a是否含有属性x: True
a是否含有属性y: False
a是否含有属性y: 19

类似__xxx__的属性和方法在Python中都是有特殊用途的。

比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法

发布了70 篇原创文章 · 获赞 29 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/LOVEYSUXIN/article/details/103387964