Can I add methods to built in types with classes?
CC
crobc at BOGUS.sbcglobal.net
Sun Aug 19 19:20:03 EDT 2007
Hi:
I've gotten through most of the "9. Classes" section of the tutorial. I
can deal with the syntax. I understand the gist of what it does enough
that I can play with it. But am still a long way from seeing how I can
use this OOP stuff.
But I have one idea. Not that the functional approach isn't workable,
but I have a situation where I need to test if all the characters in a
string are in the set of hexadecimal digits.
So 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)
But can I create a class which inherits the attributes of the string
class, then add a method to it called ishex()? Then I can do:
if string.ishex():
value = int(string, 16)
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 do:
---------------------------------------
class EnhancedString(BaseStringType):
def ishex(self):
for d in word:
if d not in hexdigits: return(False)
else return(True)
---------------------------------------
Thanks.
--
_____________________
Christopher R. Carlen
crobc at bogus-remove-me.sbcglobal.net
SuSE 9.1 Linux 2.6.5
More information about the Python-list
mailing list