1、type()
type(123)
<class 'int'>
type('str')
<class 'str'>
type(None)
<type(None) 'NoneType'>
2、isinstance()
a = Animal()
d = Dog()
h = Husky()
isinstance(h, Dog)
True
isinstance(h, Animal)
True
isinstance(d, Dog) and isinstance(d, Animal)
True
isinstance(d, Husky)
False
3、dir()
dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
4、hashattr()、setattr()、getattr(),可直接操作对象的状态
hashattr() 判断是否有属性
setattr() 添加属性
getattr() 获取属性
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
>>> hasattr(obj, 'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # 有属性'y'吗?
False
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
>>> hasattr(obj, 'y') # 有属性'y'吗?
True
>>> getattr(obj, 'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19
网友评论