Can I add methods to built in types with classes?

Scott David Daniels daniels at dsl-only.net
Sun Aug 19 19:48:51 EDT 2007


CC wrote:
> ... But am still a long way from seeing how I can use this OOP stuff.
> ... I wrote:
> from string import hexdigits
>     def ishex(word):
>         for d in word:
>             if d not in hexdigits: return(False)
>         else return(True)
> Then I can do this to check if a string is safe to pass to the int() 
> function without raising an exception:
>     if ishex(string):
>         value = int(string, 16)

The Pythonic way to do this is simply:
       try:
           value = int(string, 16)
       except ValueError:
           <something else>

> ... Can I create a class which inherits the attributes of the string 
> class, then add a method to it called ishex()? ...
 > The thing is, it doesn't appear that I can get my hands on the base
 > class definition/name for the string type to be able to ....

      class MyStr(str):
          def ishex(self):
              try:
                  value = int(self, 16)
              except ValueError:
                  return False
              return True
# in fact, you could even say
#    class MyStr(type('123')): ...




More information about the Python-list mailing list