Python inheritance and the issue of default values being overridden

Currently experimenting with inheritance in Python and encountering an issue where a field labeled famil gets overwritten by the previous instance's input when no value is provided for famil.

 class Person:
    def __init__(self, famil=[], name="Jim"):
        self._family = famil
        self._name = name

    def get_family(self):
        return self._family

    def get_age(self):
        return self._age


class Woman(Person):
    def __init__(self, family=[], name="Jane"):
        print(family)
        Person.__init__(self, family, name)

    def add_family(self, name):
        self._family += [name]


if __name__ == "__main__":
    a = Woman()
    a.add_family("john")
    print(a.get_family())
    b = Woman()
    print(b.get_family())
    print(a.get_family())

Expected Output:

[]
['John']
[]
[]
['John']

The behavior is perplexing as I am seeking to understand the concept of inheritance, expecting instances 'a' and 'b' to be independent from each other.

Answer №1

In the discussions, it was pointed out that there is an issue with mutable default arguments in Python. For further details, you can refer to

To handle this situation effectively, the recommendation is to use non-mutable default arguments and assign the default value if none is provided. Here's an example:

class Person:
    def __init__(self, family=None, name="Jim"):
        self._family = family or []
        self._name = name

class Woman(Person):
    def __init__(self, family=None, name="Jane"):
        super().__init__(self, family or [], name)

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

Save the Python version for future rebuilding of the virtual environment

In order to remember the package requirements for future installation in a Python virtual environment, many people use the following convention: first run pip freeze > requirements.txt, and then install the packages using pip install -r requirements.txt ...

Transmit two arguments to the Celery task with an estimated time of arrival

When using eta to schedule a task: test.apply_async(eta=datetime(2019, 8, 4, 17, 01)) I have a task in test.py that requires an argument from the view, such as 'post': app = Celery() @app.task(bind=True) def test(post, self): #somecode I ...

Combining time intervals in Python to create a larger one

Below is the dataframe provided: padel start_time end_time duration 38 Padel 10 08:00:00 09:00:00 60 40 Padel 10 10:00:00 11:30:00 90 42 Padel 10 10:30:00 12:00:00 90 44 Padel 10 11:00:00 12:30:00 90 46 ...

What is the maximum length of a list that can be shuffled using Python's random.shuffle function?

In my code, I utilize the Python built-in shuffle function (random.shuffle) to shuffle a list. The Python reference cautions that even for relatively small len(x), the number of possible permutations may exceed the period of many random number generators. ...

Using Beautiful Soup, extract various elements from a webpage in a repeated sequence

I'm trying to scrape a table that contains a loop, but I'm running into issues with extracting certain elements. <ul> <li class="cell036 tal arrow"><a href=" y/">ALdCTL</a></li> <li class="cell009">5,71</li ...

retrieving a colorbar tick from matplotlib that falls beyond the dataset boundaries, intended for use with the

I am attempting to utilize a colorbar to label discrete, coded values shown using imshow. By utilizing the boundaries and values keywords, I am able to achieve the desired colorbar where the maximum value is effectively 1 greater than the maximum data valu ...

Use various cumxxx functions (such as sum, min, etc.) on a DataFrame with a window of changing size

Implementing a cumxxx operation on a variable-sized window within a DataFrame is the goal. Taking into account the provided inputs: import pandas as pd from random import seed, randint from collections import OrderedDict p5h = pd.period_range(start=&apos ...

In Selenium with Java, we utilize @FindBys and @FindAll annotations to locate elements. How can we achieve the same functionality in Python using a single

I am curious about how to use @FindBys and @FindAll in Selenium Java to locate elements in Python. Can anyone provide guidance on this? @FindBys( { @FindBy(className = "class1") @FindBy(className = "class2")} ) Your help is much apprec ...

Filtering sessions by length in a pandas DataFrame: A step-by-step guide

I am working with a sizable DataFrame in pandas that contains approximately 35 million rows, with an average sequence length of about 22: session id servertime 1 3085 2018-10-09 13:20:25.096 1 3671 2018-10-21 08:19:39.0 ...

Substitute values in a dataframe using various conditions of varying lengths

When it comes to replacing dataframe values based on conditions of differing lengths, I've found success with conditions of similar length but struggle with longer or more complex conditions. Take a look at the example below: This method is effective ...

Using the key from a nested CSV file as the primary key in Python

Sorry for the confusing title. I have a csv file with rows structured like this: 1234567, Install X Software on Y Machine, ServiceTicket,"{'id': 47, 'name': 'SERVICE BOARD', '_info': {'board_href': ' ...

Is there a way to delete specific characters from a tuple that I have created using Python and appJar?

After creating a tuple using an SQL statement, I'm facing an issue when trying to print it in a text box. Some items are displaying with extra symbols like {}. For example, the item {The Matrix} has these characters, while singular items such as Incep ...

Python Selenium (Extracting Data from a Specific Table)

Picture of the table I would like to utilize My intention was to extract a specific value from the table, targeting a precise row and column. However, upon inspecting the sheet, there doesn't seem to be a <table> element present, leaving me str ...

Error encountered in Selenium with Python when trying to locate Chrome binary for outdated versions of the browser: WebDriverException - Chrome binary not found

Due to compatibility reasons, I have opted to use Chrome version 55.0.2883.75 with Chromedriver v. 2.26. To download the older version of Chrome, I visited , and for Chromedriver 2.26, I got it from https://chromedriver.storage.googleapis.com/index.html?pa ...

Getting the LSTM ready for classifying time-series data using TensorFlow

I am currently working on a TensorFlow model designed to assign a continuous label to each time-step of a time-series. The goal is for this model to operate in real-time, where the values observed in previous time-steps will influence the label attributed ...

Unable to access a static file via a static URL with django.test.client

Environment Details Python Version: 3.8.14 Django Version: '4.2.4' Purpose of the Task Ensure that the static file is properly saved Ensure that the static file can be accessed from a web browser Issue Faced The problem arises after runnin ...

Employing Python with Selenium to programmatically click on a button with a ng-click attribute and automatically upload

I am completely new to using Python and Selenium, but I have a task that requires me to automate file uploads with Selenium. There is a button that needs to be clicked which will launch a window for selecting the file to upload. Here is the HTML code fo ...

Triggering specialized Timeouts when waiting for certain elements

This question is a continuation of my previous inquiry regarding inconsistencies in scraping through divs using Selenium. Currently, I am working on extracting Air Jordan Data from grailed.com's selection of high-top sneakers by Jordan Brand. My objec ...

Create a new instance of a class without considering letter case

Currently, I am dealing with a dilemma. My class name is stored in a variable, and I need to create an instance of it. However, the problematic part is that I cannot guarantee that my variable has the same casing as the class name. For example: //The cla ...

Fixing the error 'Element <option> could not be scrolled into view' is a common issue that many users encounter

Every time I try to select a value from a dropdown using Selenium webdriver, I encounter nothing but errors. My objective is simple - I just want to choose Ubuntu 16.04 from the OS dropdown menu. I attempted to click on the dropdown and then on the Ubuntu ...