1、type()
获取基本数据类型都可以用type()
>>> type(123)
<class 'int'>
>>> type(123) == int
True
>>> type('aaa')
<class 'str'>
>>> type('aaa') == str
True
如果是判断一个对象是不是函数呢?可以用types模板中定义的常量
>>> import types
>>> class Student(object):
... pass
...
>>> type(Student()) == types.FunctionType
False
>>> def demo():
... pass
...
>>> type(demo)
<class 'function'>
>>> type(demo) == types.FunctionType
True
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(abs) == types.BuiltinFunctionType
True
>>> type(lambda x: x) == types.LambdaType
True
2、isinstance()
如果有继承关系,用type()就不方便,此时我们可以用isinstance()来判断。
>>> class Animal(object):
... pass
...
>>> class Cat(Animal):
... pass
...
>>> class Dog(Animal):
... pass
...
>>> class LittleDog(Dog):
... pass
...
>>> c = Cat()
>>> d = Dog()
>>> ld = LittleDog()
>>>> isinstance(c, (Animal)) #Cat继承了Animal,所以为True
True
>>> isinstance(ld, (Dog)) #LittleDog继承了Dog,所以为True
True
>>> isinstance(ld, (Animal)) #Dog继承了Animal,而LittleDog继承了Dog,所以为True
True
>>> isinstance(ld, (Cat)) #LittleDog没有继承Cat,所以为false
False
>>>
type()能判断的,isinstance()都可以判断:
>>> isinstance(123, (int))
True
>>> isinstance('aaa', (str))
True
isinstance()还可以判断变量是不是多个类型中的一种:
>>> isinstance('aaa', (int, str))
True
>>> isinstance('123', (int, str))
True
>>>
3、dir()函数
dir()函数可以获取对象的所有方法和属性。
>>> class Student(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
... def print_student(self):
... print('学生姓名:%s, 年龄:%d' %(self.name, self.age))
...
>>> s = Student('张三', 18)
>>> dir(s)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_s
ubclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclas
shook__', '__weakref__', 'age', 'name', 'print_student']
>>>
getattr()、setattr()以及hasattr(),可以直接操作一个对象的状态:
hasattr():判断对象是否有该属性
>>> class Student(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
... def print_student(self):
... print('学生姓名:%s, 年龄:%d' %(self.name, self.age))
...
>>> s = Student('张三', 18)
>>> hasattr(s, 'name') #判断s对象内是否有name属性,name要用双号,有为True,没有为false
True
>>> hasattr(s, 'age')
True
>>> hasattr(s, 'x')
False
>>>
getattr():获取指定对象的属性值
setattr():设置指定对象的属性值
>>> getattr(s, 'name')
'张三'
>>> getattr(s, 'age')
18
>>> getattr(s, 'x') #没有该属性会报AttributeError错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'x'
>>> getattr(s, 'x', 404) #当没有该属性的时候,可以添加第三个参数指定返回
404
>>> getattr(s, 'print_student') #获取s对象内的print_student()方法
<bound method Student.print_student of <__main__.Student object at 0x00000000021
E8358>>
>>> p = getattr(s, 'print_student') #获取属性'print_student'并赋值到变量p
>>> p() #调用p即调用print_student
学生姓名:李四, 年龄:11
>>> setattr(s, 'name', '李四') #给name属性的赋值
>>> getattr(s, 'name')
'李四'
>>> setattr(s, 'age', 11)
>>> getattr(s, 'age')
11
>>>