1

I want to add custom properties to the standard Python types (e.g. a size property to the str type), but the code below doesn't seem to do the trick; I get AttributeError: 'str' object has no attribute 'size'. What's wrong?

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
Lucca
  • 175
  • 1
  • 1
  • 12
  • 1
    First, I doubt you have a good use case to monkey-patch string. Second, i doubt there is an easy way since it's C-implemented (for CPython of course) – Chris_Rands Aug 27 '18 at 15:16
  • But assuming I had a good reason to monkey-patch string, how would I go about doing this? – Lucca Aug 27 '18 at 15:21
  • Can you give us the good reason? (I think there is likely a better way to solve your actual issue) – Chris_Rands Aug 27 '18 at 15:21
  • 1
    Have a look at https://stackoverflow.com/questions/44204937/is-there-any-way-to-override-pythons-built-in-class – Mia Aug 27 '18 at 15:26

0 Answers0