how to make child class call parent class __init__ automatically?

2024/11/17 17:36:23

i had a class called CacheObject,and many class extend from it.

now i need to add something common on all classes from this class so i write this

class CacheObject(object):def __init__(self):self.updatedict = dict() 

but the child class didn't obtain the updatedict attribute.i know calling super init function was optional in python,but is there an easy way to force all of them to add the init rather than walk all the classes and modify them one by one?

Answer

I was in a situation where I wanted classes to always call their base classes' constructor in order before they call their own. The following is Python3 code that should do what you want:

  class meta(type):def __init__(cls,name,bases,dct):def auto__call__init__(self, *a, **kw):for base in cls.__bases__:base.__init__(self, *a, **kw)cls.__init__child_(self, *a, **kw)cls.__init__child_ = cls.__init__cls.__init__ = auto__call__init__class A(metaclass=meta):def __init__(self):print("Parent")class B(A):def __init__(self):print("Child")

To illustrate, it will behave as follows:

>>> B()
Parent
Child
<__main__.B object at 0x000001F8EF251F28>
>>> A()
Parent
<__main__.A object at 0x000001F8EF2BB2B0>
https://en.xdnf.cn/q/71191.html

Related Q&A

Creating a dataframe in pandas by multiplying two series together

Say I have two series in pandas, series A and series B. How do I create a dataframe in which all of those values are multiplied together, i.e. with series A down the left hand side and series B along t…

UnicodeDecodeError in PyCharm debugger

Its a reference to UnicodeDecodeError while using cyryllic .I have same problem with Python 3.3 and Pycharm 2.7.2 Tryed to hardcode encoding in code, manually specifying encoding in Pycharm options, bu…

Scipy griddata with linear and cubic yields nan

the following code should produce griddata. But in case I choose as interpolation type cubic or linear I am getting nans in the z grid. Wen im choosing nearest everything is running fine. Here is an ex…

Clone a module and make changes to the copy

Is it possible to copy a module, and then make changes to the copy? To phrase another way, can I inherit from a module, and then override or modify parts of it?

AWS Lambda, Python, Numpy and others as Layers

I have been going at this for a while trying to get python, numpy and pytz added to AWS Lambda as Layers rather than having to zip and throw it at AWS with my .py file. I was able to follow multiple tu…

Is there a way to check if a module is being loaded by multiprocessing standard module in Windows?

I believe on Windows, because there is no fork, the multiprocessing module reloads modules in new Pythons processes. You are required to have this code in your main script, otherwise very nasty crashes…

Condas solving environment takes forever

I am using conda since one year, since several weeks, whenever I want to install a package using conda install -c anaconda <package_name>, for any package, it is just stuck at the Solving environ…

How to overwrite a file in Python?

Im trying to overwrite a file. I based my answer on this Read and overwrite a file in PythonTo complete my codes:<select class="select compact expandable-list check-list" ONCHANGE="lo…

Is os.popen really deprecated in Python 2.6?

The on-line documentation states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:>>> import os >>> [c.close() for c in os…

Routes with trailing slashes in Pyramid

Lets say I have a route /foo/bar/baz. I would also like to have another view corresponding to /foo or /foo/. But I dont want to systematically append trailing slashes for other routes, only for /foo a…