我想将自定义属性添加到标准Python类型(例如,将size
属性添加到str
类型),但是下面的代码似乎并不能解决问题;我得到AttributeError: 'str' object has no attribute 'size'
。怎么了?
import __builtin__
class str2(str):
def __init__(self, text):
super(str2, self).__init__(text)
self.size = len(self)
__builtin__.str = str2
print str2("foo").size # This works
print str("bar").size # This also works
print "baz".size # But this doesn't