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 doesn't work... I expect that if I work in color_extended.py, 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

Thanks


Solution 1:

Use:

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.

Solution 2:

class MyParent:

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

class ChildClass(MyParent):
    pass

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

Solution 3:

Eu uso assim. I use it like this.

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

def metodo1(self)
  print(self.propriedade1)

para extender. 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):
    self.menssagem1.metodo1()