Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 466
omega Avatar asked Mar 20 '13 14:03

omega


People also ask

How do you extend a class?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

What does it mean to extend a class Python?

In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism.

Can a method extend a class?

No. You can extend the class and override just the single method you want to "extend".


2 Answers

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.

like image 130
NPE Avatar answered Nov 08 '22 09:11

NPE


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.

like image 34
mehov Avatar answered Nov 08 '22 08:11

mehov