class unicode (__builtins__.unicode):
def __new__ (cls, u=""):
self = __builtins__.unicode.__new__(cls, u)
return self
# So, you do it just once and then you can:
def add_check (obj):
obj.IsNullOrEmpty = lambda: not obj
u1 = unicode("12345")
u2 = unicode()
add_check(u1)
add_check(u2)
print u1.IsNullOrEmpty()
print u2.IsNullOrEmpty()
class MyStr(str):
def is_null_or_empty(self): # see PEP 8 for naming conventions
return not bool(self)
str1, str2 = MyStr("non-empty"), MyStr("")
print(str1.is_null_or_empty(), str2.is_null_or_empty())
下面是一个调整数据类型以接受外部属性的示例:
注:使用:
将产生内置的.unicode(),而不是我们修改过的类型,因此您必须是显式的
您可以扩展Python内置类型,不过如果您不小心,可能会发现自己在处理一些奇怪的情况。例如:
应该打印
请注意,所有从基类(系统
str
类型)继承并返回字符串的方法将继续返回简单字符串,而不是MyStr
实例。要让它们返回这样的实例,类需要包装每个这样的方法。以下是upper
方法的示例:这里
super().upper()
是对超类(i,.e.)的调用,str
的upper
方法,其中self
作为当前实例(因此作为参数1传递给该方法)-它不能再简单地从self
继承和引用,因为upper
的MyStr
定义将首先被解析,从而导致无限递归相关问题 更多 >
编程相关推荐