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
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.
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.
No. You can extend the class and override just the single method you want to "extend".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With