Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Python class init

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.

like image 570
MFB Avatar asked Oct 03 '12 02:10

MFB


People also ask

How do you extend a class in 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.

What is super () __ Init__ in Python?

__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.

What is __ init __ () in Python?

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.

How do you extend a class from another class in Python?

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.


1 Answers

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):     ... 
like image 89
Jesse Avatar answered Sep 28 '22 23:09

Jesse