我在 python 2 和 3 中使用数据类型来断言唯一值。否则我不能让它们像 str 或 int 类型一样工作。但是,如果您需要检查一个可以具有任何类型的值除了特定类型,那么它们非常有用并且可以使代码更好地阅读。
继承对象会在 python 中创建一个类型。
class unset(object):
pass
>>> print type(unset)
<type 'type'>
示例使用:您可能希望使用条件或函数处理程序有条件地过滤或打印值,因此使用类型作为默认值会很有用。
from __future__ import print_function # make python2/3 compatible
class unset(object):
pass
def some_func(a,b, show_if=unset):
result = a + b
## just return it
if show_if is unset:
return result
## handle show_if to conditionally output something
if hasattr(show_if,'__call__'):
if show_if(result):
print( "show_if %s = %s" % ( show_if.__name__ , result ))
elif show_if:
print(show_if, " condition met ", result)
return result
print("Are > 5)")
for i in range(10):
result = some_func(i,2, show_if= i>5 )
def is_even(val):
return not val % 2
print("Are even")
for i in range(10):
result = some_func(i,2, show_if= is_even )
输出
Are > 5)
True condition met 8
True condition met 9
True condition met 10
True condition met 11
Are even
show_if is_even = 2
show_if is_even = 4
show_if is_even = 6
show_if is_even = 8
show_if is_even = 10
如果show_if=unset 是完美的用例,因为它更安全且可读性好。我还在枚举中使用了它们,这在 python 中并不是真正的东西。