all
all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 True,如果是返回 True,否则返回 False。
元素除了是 0、空字符串、None、False 外都算 True。
语法:all(iterable)。
常用语判断和map
结合使用
# 假如需要判断 可迭代对象 (相同长度)s 和 e 对应的每个值是否相同
all(map(lambda x: x[0] == x[1], zip(s, e)))
all((True, True, False)) # 返回 false
all((0, 1, 2, 3, 4)) # 返回 false
any
any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True—有一个为真就为真,否全部为假就是假
。
元素除了是 0、空字符串、False 外都算 True。
any((True, False, False))
any(('', None, False, 0, True))
# 全部为true
isinstance
isinstance
函数来判断一个对象是否是一个已知的类型,类似 type
。返回true或者false
isinstance() 与 type() 区别:
- type() 不会认为子类是一种父类类型,不考虑继承关系。
- isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。
语法
isinstance(x, a_tuple)
注意
:a_tuple只能是一个类或者元组并且元组中每个元素是类
class Test:
def hello(self, ):
print('hello')
t = Test()
isinstance(t.hello, Test) # True
isinstance('a', str) # True pyton 一切皆对象。本质字符串是 str 的一个子类
print(isinstance('a', (str, list))) # True
getattr
getattr函数用于返回一个对象属性值
语法
getattr(object, name[, default])
常用于字符串转属性或者判定某个对象中是否存在值
class Test:
def hello(self, ):
print('hello')
t = Test()
hello = getattr(t, 'hello')
hello()
# 如果不确定是否存在某个属性可以给一个默认值,不存在返回默认值
test = getattr(t, 'test', None)
setattr
语法
setattr(object, name, value)
setattr
函数对应函数 getattr,用于设置属性值,该属性不一定是存在的
class Test:
def hello(self, ):
print('hello')
t = Test()
# hello = getattr(t, 'hello')
# hello()
# t 对象设置 属性a 值为b
setattr(t, 'a', 'b')
print(t.a)
django 类视图 设置 属性源码
class View:
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = [
"get",
"post",
"put",
"patch",
"delete",
"head",
"options",
"trace",
]
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.items():
setattr(self, key, value)