来判断一个对象是否是一个已知的类型。
语法:isinstance(object, classinfo) -> bool
参数:
返回值:
isinstance() 与 type() 区别:
示例:
class A: pass
class B(A): pass
isinstance(A(), A) # True
type(A()) == A # True
isinstance(B(), A) # True
type(B()) == A # False
用于判断对象是否包含对应的属性。
语法:hasattr(object, name: str) -> bool
参数:
返回值:
示例:
class Coordinate:
x = 10
point1 = Coordinate()
hasattr(point1, 'x') # True
hasattr(point1, 'y') # False
返回一个对象属性值。
语法:getattr(object, name[, default])
参数:
返回值:
示例:
class A:
bar = 'bar的值'
a = A()
getattr(a, 'bar') # 'bar的值'
getattr(a, 'bar2', '没有该属性') # '没有该属性'
设置属性值,该属性不一定是存在的。
语法:setattr(object, name, value) -> None
参数:
返回值:
示例:
class A:
bar = 'bar的值'
a = A()
getattr(a, 'bar') # 'bar的值'
getattr(a, 'bar2', '没有该属性') # '没有该属性'
setattr(a, 'bar2', 'bar2的值')
getattr(a, 'bar2', '没有该属性') # 'bar2的值'
调用父类(超类)的一个方法。
语法:super(type[, object-or-type])
参数:
返回值:
示例 python3:
class F:
def __init__(self):
print('F')
class A(F):
def __init__(self):
print('A')
class B(A):
def __init__(self):
super().__init__()
b = B() # 'A'
示例 python2:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class F(object): # Python2.x 需要继承 object
def __init__(self):
print('F')
class A(F):
def __init__(self):
print('A')
class B(A):
def __init__(self):
super(B, self).__init__()
b = B() # 'A'