invoking the parent class in a subclass in Python version 2.7

Recently, I've been delving into the world of OOP in Python and trying to grasp some basic concepts. One question that popped up was related to subclassing a class like list and how to properly invoke the parent constructor. After experimenting a bit, I stumbled upon the following syntax:

super(subclass_name, self).__init__(args)

But what puzzles me is why can't we simply use something like list(args) or list.__init__(args)?

Below is a snippet of the code where this issue arises:

class slist(list):
  def __init__(self, iterable):
    # super(slist, self).__init__(iterable)  <--- This works
    list.__init__(iterable) # This does not work
    self.__l = list(iterable)

  def __str__(self):
    return ",".join([str(s) for s in self.__l])

Answer №1

The method list.__init__(iterable)
does not specify which list to initialize, while list(iterable) creates a new and separate list that is not related to the one you want to initialize.

If you prefer not to utilize super, an alternative approach is list.__init__(self, iterable).

Answer №2

It is not correct to use list.__init__(iterable)
. You must specify which object __init__() is initializing. Avoid using list(args) as it creates a new list object instead of initializing your current one. In this case, it invokes list.__new__() rather than list.__init__(). Ensure to pass self in the constructor call for proper initialization:

list.__init__(self, args)

This approach will successfully initialize the parent class. Alternately, utilizing super() can lead to more concise syntax. Here's an alternative form of the above code:

super(slist, self).__init__(args)

The primary advantage of using super() lies in scenarios involving multiple inheritance. It handles the invocation of each parent class' constructor automatically and in the right sequence. This concept is closely tied to Python's Method Resolution Order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``I couldn't keep up with Mario's lightning speed as he dashed across

Let's take a look at the code snippet below: import pygame, sys from pygame.locals import * class Person(pygame.sprite.Sprite): def __init__(self, screen): self.screen = screen pygame.sprite.Sprite.__init__(self) s ...

Generate a dataframe by combining several arrays through an iterative process using either a for loop or a nested loop in

I am currently working on a project involving a dataframe where I need to perform certain calculations for each row. The process involves creating lists of 100 numbers in step 1, multiplying these lists together in step 2, and then generating a new datafra ...

Transform a wide data frame into long format using Python

I attempted to transform a dataframe from wide format to long format following the instructions provided at this link df = pd.DataFrame({'Mode': ['car', 'car', 'car', 'air', 'air', 'car&apos ...

Exploring the manual functions of Selenium

When running tests in Selenium, I often find myself manually clicking and entering data in the fields of my browser. Is there a way to capture and save these manual actions as logs? I'm curious to see exactly what actions the user takes during a manu ...

Scipy installation unsuccessful

Looking for assistance with installing scipy 1.2.0 for python2.7 on a machine running rhel fedora 6.5 without sudo permissions. Python2.7, numpy, ATLAS, and openblas are already installed. Encountering an error when trying to run "@python2.7 setup.py bui ...

Best method for releasing a string returned from a C function in CFFI?

ffi = FFI() C = ffi.dlopen("mycffi.so") ffi.cdef(""" char* foo(T *t); void free_string(char *s); """) def get_foo(x): cdata = C.foo(x) s = ffi.string(cdata) ret = s[:] C.free_string(cdata) return ret If a char * is passed from a C f ...

Replit facing issues with installing required packages

Recently, I attempted to utilize replit as a temporary online host while searching for a free hosting service. Unfortunately, when attempting to install dependencies on the platform, I encountered an error resembling the following: Traceback (most recent ...

Transforming a pandas Dataframe into a collection of dictionaries

Within my Dataframe, I have compiled medical records that are structured in this manner: https://i.stack.imgur.com/O2ygW.png The objective is to transform this data into a list of dictionaries resembling the following format: {"parameters" : [{ ...

Press the 'Export' CSV option within a SharePoint List using Selenium

To complete a CSV download from a SharePoint list, I need to click on two buttons located in the top command bar. https://i.stack.imgur.com/zTTyJ.png https://i.stack.imgur.com/Z9zB1.png Despite using the 2 locators and an explicit wait mentioned below, I ...

User 'root' at address '10.x.x.x' has been denied access to Flask-Migrate due to an incorrect password

I'm currently working with Flask-Migrate and MySQL in my project. While running the code, I encountered an error message: sqlalchemy.exc.OperationalError: (MySQLdb.OperationalError) (1045, "Access denied for user 'root'@'10.x.x. ...

Storing a collection in redis-py

Attempting to save a list created from a dictionary into my redis database, I am running the following script: x = {'TLV-IST#2022-12-27~2023-01-04': '252', 'TLV-IST#2022-12-27~2023-01-17': '300'} for key, value in x ...

How can I transform a list of company names into corresponding LinkedIn links using a scraper tool?

Using Python, Selenium, and BeautifulSoup, I created a custom LinkedIn scraper that extracts relevant information about companies from their LinkedIn profiles such as details on competitors. However, my current challenge lies in managing a list of company ...

"Unveiling the secret of wrapping an XML tag with the python library, xmltodict

Below is the desired xml output: <?xml version="1.0" encoding="utf-8"?> <fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <foo> <bar>1</bar> &l ...

Using an SAS token to access Azure Blob storage in Python

UPDATE: I need to retrieve a blob from an Azure Storage Container and incorporate it into my Python script using a unique SAS Token specific to BLOB. from azure.storage.blob import BlobService sas_service = BlobService( account_name = "name", sas ...

Parsing problem that defies logic while attempting web scraping with BeautifulSoup

I'm currently attempting to use the script below to iterate through a list of URLs, extract the date and location information for each race per URL. However, I keep encountering an IndexError that seems quite perplexing as the lists I am working with ...

What is the best way to combine numerous dictionaries and sum up the values of matching keys? (Python)

Imagine having the following sets of dictionaries: dict1 = {'a': 10, 'b': 8, 'c':3} dict2 = {'c': 4} dict3 = {'e':9, 'a':3} The goal is to combine them in such a way that the new resulting dictio ...

Python Selenium script for entering a date into an AngularJS datepicker

I am having trouble entering a date into a text field of a datepicker using send_keys in Selenium. Here is the HTML code snippet: <date-picker _ngcontent-bdp-c11="" _nghost-bdp-c3=""> <div _ngcontent-bdp-c3="" cl ...

Drag and drop a file onto the center of the screen to upload it using Python

I need to upload a file to a website using Python Selenium, but because I am working in headless mode, I cannot click on the upload file button. Is there a way for me to automatically upload a file by dropping it in the center of the screen? I attempted th ...

What is the method for merging multiple Django querysets without combining them?

Having recently started working with the Django framework, I'm facing an interesting challenge that may be of interest to more experienced developers here. Here is the django model in question: STATUS_CHOICES = ( ('CL', 'CLOSED&apo ...

Pressing the 'View More' option within Google Scholar search outcomes

My current challenge involves scraping a Google Scholar page, where I am only able to retrieve the initial twenty results displayed. To overcome this limitation, I have been experimenting with Selenium in an attempt to click on the 'show more' bu ...