隨手扎
MyString委派(delegate)加法
之前擴展String的+方法。不過這樣的實現不是很彈性:
count = 10
"-"*10
# "Count: " + count # will rise exception
"Count: " + str(count) # allow string + string
class myString(str):
def __add__(self, other):
if other == None:
return myString(str(self) + "None")
elif type(other) == str:
return myString(str(self) + other)
elif type(other) == int or type(other) == float:
return myString(str(self) + str(other))
else:
return myString(str(self) + str(other))
myString("Count: ") + count # success. => 'Count: 10'
myString("Count: ") + count + " and " + count # => 'Count: 10 and 10'
myString("Count: ") + None # => 'Count: None'
這次來稍微修改,改用委派的方式。
class myString(str):
__delegate_table = {
type(None): lambda self, other: myString(str(self) + "None"),
str: lambda self, other: myString(str(self) + other),
int: lambda self, other: myString(str(self) + str(other)),
float: lambda self, other: myString(str(self) + str(other)),
}
@staticmethod
def __default(self, other):
return myString(str(self) + str(other))
def __add__(self, other):
return self.__delegate_table.get(type(other), self.__default)(self, other)
@classmethod
def delegate(clz, key, method):
clz.__delegate_table[key] = method
myString("Count: ") + count # success. => 'Count: 10'
myString("Count: ") + count + " and " + count # => 'Count: 10 and 10'
myString("Count: ") + None # => 'Count: None'
myString("Type int: ") + int # => "Type int: <class 'int'>"
myString("").delegate(type, lambda self, other: myString("Hello, Type: " + str(self)))
myString("Type int: ") + int # => 'Hello, Type: Type int: '
如此一來,就可以動態增減處理方法。如上面,增加對於type
的處理。