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

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

import Color

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

But this doesn’t work…
I expect that if I work in, then when I make a 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 the init from the import.

Assume python 3.1



import color

class Color(color.Color):

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):

This is not necessary in Python 3.x.

class MyParent:

    def sayHi():
        print('Mamma says hi')
from import MyParent

class ChildClass(MyParent):

An instance of ChildClass will then inherit the sayHi() method.

I use it like this.

class menssagem:
  propriedade1 = "Certo!"
  propriedade2 = "Erro!"

def metodo1(self)

to extend.

import menssagem
class menssagem2(menssagem):

  menssagem1 = None #não nescessario not necessary

  def __init__(self,menssagem):
    self.menssagem1 = menssagem

  #call first class method
  #usando o metodo da menssagem 1

  def Menssagem(self):

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I’ve done this to extend Python 2’s str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here’s some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

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

After which I can write in the code fed to the preprocessor:

if ''.testDottedQuad():

dq = '216.126.621.5'
if not dq.testDottedQuad():

if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor 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.