1. getattr():
官网文档如下 def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
getattr(x, "y") 相当于x.y,即 获取对象x的y属性的值,如有有默认值,当属性不存在时会返回默认值,如果没有默认值并且属性不存在时,就会报错AttributeError。
举例说明:
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
print(getattr(functiondemo, 'name')) #获取 name 属性,存在就打印出来--- demo
print(getattr(functiondemo, "run"))
# 获取 run 方法,存在打印出方法的内存地址
# <bound method function_demo.run of <__main__.function_demo object at 0x006E8A10>>
# print(getattr(functiondemo, "age"))
# 获取不存在的属性,报错如下:
# Traceback (most recent call last):
# File "F:/Python/PycharmProjects/Mytest_code/tmp.py", line 11, in <module>
# getattr(functiondemo, "age")
# AttributeError: 'function_demo' object has no attribute 'age'
print(getattr(functiondemo, "age", 18)) #获取不存在的属性,返回一个默认值
2. hasattr():
官方文档为: def hasattr(*args, **kwargs): # real signature unknown """ Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
hasattr():返回布尔值,是否拥有对象的某个属性值。
举例说明:
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
print(hasattr(functiondemo, 'name')) #判断对象是否有 name 属性,True
print(hasattr(functiondemo, "run")) #判断对象是否有 run 方法,True
print(hasattr(functiondemo, "age")) #判断对象是否有 age 属性,False
3. setattr():
官方文档:
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass
setattr实际上就是给对象x的y属性赋值,类似x.y = v。还可以搭配hasattr和getattr。
举例说明:
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
print(hasattr(functiondemo, 'age'))# 判断 age 属性是否存在,False
setattr(functiondemo, 'age', 18 ) #对 age 属性进行赋值,无返回值
print(hasattr(functiondemo, 'age')) #再次判断属性是否存在,True
综合使用:
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
if hasattr(functiondemo, 'addr'):# 先判断是否存在
addr = getattr(functiondemo, 'addr')
print(addr)
else:
addr = getattr(functiondemo, 'addr', setattr(functiondemo, 'addr', '首都北京'))
#addr = getattr(functiondemo, 'addr', '美国纽约')
print(addr)
4. issubclass():
官方文档:
def issubclass(x, A_tuple): # real signature unknown; restored from __doc__ """ Return whether 'cls' is a derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) or ...`` etc. """ pass
issubclass()方法用于判断参数x是否是类型参数A_tuple的子类。第二个参数还可以是个元组,让第一个参数分别去元组中匹配,如果有所属的类满足条件,则返回为True,反之,False。
举例说明:
class A:
pass
class AA:
pass
class BB:
pass
class B(A):
pass
print(issubclass(B, (A, AA))) # 返回 True
print(issubclass(B, (BB, AA))) # 返回 False
5. isinstance():
官方文档:
def isinstance(x, A_tuple): # real signature unknown; restored from __doc__ """ Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc. """ pass
isinstance() 用于判断一个对象是不是指定的类型,如果是则返回True,否则返回False。
举例说明:
In [11]: isinstance("hello", str)
Out[11]: True
In [12]: isinstance(123, int)
Out[12]: True
In [13]: isinstance(123, (str, int, list)) # 第二个参数也可以是一个元组,只要是元组内的某一个类型即可返回True
Out[13]: True