How to extend a class in python?

In python, how can you extend a class? For example, if I have

color.py

class Color: def __init__(self, color): self.color = color def getcolor(self): return self.color 

color_extended.py

 import Color class Color: def getcolor(self): return self.color + " extended!" 

But this does not work ... I expect that if I work in color_extended.py , then when I create the color object and use the getcolor function, then it will return the object with the string "extended!". in the end. Also it should have gotton init from import.

Assume python 3.1

thank

+70
python class interface
Mar 20 '13 at 14:48
source share
2 answers

Using:

 import color class Color(color.Color): ... 

If this is Python 2.x, you would also like to get color.Color from object to make it a new-style class :

 class Color(object): ... 

This is not necessary in Python 3.x.

+74
Mar 20 '13 at 14:50
source share
— -

Another way to extend (in particular, add new methods, rather than modify existing) classes, even built-in ones, is to use a preprocessor that adds the ability to extend the scope of Python itself or go beyond it, converting the extension to normal Python syntax before Python will really see it.

I did this to extend the Python 2 class str() , for example. str() is a particularly interesting target because of the implicit connection to the data in quotation marks, such as 'this' and 'that' .

Here is some extensible code in which the only non-Python syntax added is the extend:testDottedQuad :

 extend:testDottedQuad def testDottedQuad(strObject): if not isinstance(strObject, basestring): return False listStrings = strObject.split('.') if len(listStrings) != 4: return False for strNum in listStrings: try: val = int(strNum) except: return False if val < 0: return False if val > 255: return False return True 

Then I can write in the code passed to the preprocessor:

 if '192.168.1.100'.testDottedQuad(): doSomething() dq = '216.126.621.5' if not dq.testDottedQuad(): throwWarning(); dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad() if dqt: print 'well, that was fun' 

The preprocessor eats this, spits out normal Python without patches for monkeys, and Python does what I intended to do.

Just as an ac preprocessor adds functionality to c, so a Python preprocessor can add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

0
May 08 '19 at 3:41
source share



All Articles