I have created a base class:
class Thing(): def __init__(self, name): self.name = name
I want to extend the class and add to the init method so the that SubThing
has both a name
and a time
property. How do I do it?
class SubThing(Thing): # something here to extend the init and add a "time" property def __repr__(self): return '<%s %s>' % (self.name, self.time)
Any help would be awesome.
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.
__init__() Call in Python. When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
To create a class that inherits from another class, after the class name you'll put parentheses and then list any classes that your class inherits from. In a function definition, parentheses after the function name represent arguments that the function accepts.
You can just define __init__
in the subclass and call super
to call the parents' __init__
methods appropriately:
class SubThing(Thing): def __init__(self, *args, **kwargs): super(SubThing, self).__init__(*args, **kwargs) self.time = datetime.now()
Make sure to have your base class subclass from object
though, as super
won't work with old-style classes:
class Thing(object): ...
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