type()函数
判断一般的对象类型
print(type(123))
print(type('123'))
D:\annicoda\envs\untitled\python.exe "D:/day py/eleven.py"
<class 'int'>
<class 'str'>
Process finished with exit code 0
判断一个对象是否是函数
import types
def fn():
pass
print(type(fn)==types.FunctionType)
print(type(abs)==types.BuiltinFunctionType)
print(type(lambda x: x)==types.LambdaType)
print(type((x for x in range(10)))==types.GeneratorType)
D:\annicoda\envs\untitled\python.exe "D:/day py/eleven.py"
True
True
True
True
Process finished with exit code 0
isinstance()函数
判断class的类型使用isinstance()函数
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('the dog is running...')
class Cat(Animal):
def eat(self):
print('the cat is eating...')
d=Dog()
print(isinstance(d,Dog))
print(isinstance(d,Animal))
print(isinstance(d, Dog) and isinstance(d, Animal))
D:\annicoda\envs\untitled\python.exe C:/Users/33066/PycharmProjects/untitled/venv/hello.py
True
True
True
Process finished with exit code 0
isinstance()函数可以判断是否是list或者tuple:
print(isinstance([1, 2, 3], (list, tuple)))
print(isinstance((1, 2, 3), (list, tuple)))
D:\annicoda\envs\untitled\python.exe C:/Users/33066/PycharmProjects/untitled/venv/hello.py
True
True
Process finished with exit code 0
使用dir()函数
获得一个对象的所有属性和方法
print(dir('ABC'))
它返回一个包含字符串的list
D:\annicoda\envs\untitled\python.exe C:/Users/33066/PycharmProjects/untitled/venv/hello.py
['__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', 'isascii', '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']
Process finished with exit code 0