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()乾颁,可直接操作對象的狀態(tài)
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) # 設(shè)置一個屬性'y'
>>> hasattr(obj, 'y') # 有屬性'y'嗎英岭?
True
>>> getattr(obj, 'y') # 獲取屬性'y'
19
>>> obj.y # 獲取屬性'y'
19