Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a Python object keeps old values, another instance changes unexpectedly, or an override calls the wrong method, start by asking who owns the state or behavior: one function call, one instance, the class, or a place in the inheritance hierarchy. The fixes below connect each symptom to the Python rule behind it and show when to use a fresh value, deliberate sharing, or composition.

Why does my Python default list keep its old values?

Python evaluates a function’s default arguments once, when it defines the function. If that default is a list, calls that omit the argument reuse the same list.

def add_item(item, items=[]):
    items.append(item)
    return items

Calling add_item("a") and then add_item("b") returns lists that contain both values. The list is not recreated for each call.

Create per-call state inside the function

Use a sentinel such as None, then create the list when the caller has not supplied one:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Each call that omits items now gets a fresh list. If a caller does pass a list, this function still mutates that caller-owned list. If the function should not change the supplied list, copy it before appending. The Python Programming FAQ recommends avoiding mutable objects as defaults: Mutable default values.

Why is my list shared between Python objects?

A mutable class attribute belongs to the class. Instances that look up that attribute find the same list unless they have an instance attribute of that name.

class Dog:
    tricks = []

    def add_trick(self, trick):
        self.tricks.append(trick)

Here, self.tricks resolves to the class’s list until an instance attribute shadows it. Appending through one dog therefore changes the list another dog sees.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Put per-object data on each instance

class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []

    def add_trick(self, trick):
        self.tricks.append(trick)

Now each Dog receives its own list in __init__. The distinction is ownership: use an instance attribute for state that varies by object, and a class attribute when sharing is intentional, such as a constant or a shared registry. Assigning a value to self.attribute creates or updates an instance attribute; it does not change the class attribute. The Python Tutorial explains class and instance variables: Class and instance variables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does a mutable data-class field fail or get shared?

For a mutable data-class field that should belong to each instance, use field(default_factory=...). The factory is a zero-argument callable invoked when a default is needed.

from dataclasses import dataclass, field

@dataclass
class Cart:
    items: list[str] = field(default_factory=list)

Each Cart instance that uses the default gets a new list. In current Python, the data-class decorator rejects unhashable defaults as a partial safeguard against mutable defaults. This diagnostic changed in Python 3.11: earlier versions checked a narrower set of built-in mutable types, while Python 3.11 and later use unhashability as the proxy. That check does not decide whether data conceptually belongs to an instance or is meant to be shared. See the dataclasses reference on mutable defaults.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Should this class attribute be shared or belong to each instance?

Choose based on intended ownership, not merely on whether a value is mutable. A mutable class attribute is not inherently wrong: a shared registry may be intentional. The risk is treating class-owned state as if it were private to each object.

Choice Ownership Mutation and assignment Typical use
Class attribute Shared by instances that look it up through the class Mutating the object is visible through those lookups. Assigning self.name shadows the class attribute for that instance. Constants or deliberately shared registries
Instance attribute Belongs to one object Each instance can hold and mutate its own value independently. Names, per-object lists, configuration or other object-specific state

When behavior is surprising, inspect where an attribute is assigned and whether it is an instance attribute or inherited from the class. The Python Tutorial’s discussion of class and instance variables describes this lookup distinction.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my subclass method not call the method I expected?

Overriding a method changes what callers reach through that method name, so an override can surprise code that relies on the base method’s assumptions. It can also fail if it does not initialize state the rest of the class expects. Before adding or keeping a subclass, ask whether code written for the base class can use the subtype without special cases. Substitutability is a design expectation, not a rule Python enforces.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Use composition when the base interface does not fit

If the new type only needs a capability from another object, store that helper and delegate the needed operation instead of inheriting an interface the new type cannot honor. Inheritance remains useful for genuine subtype relationships and well-designed extension points; composition is a better fit when the inherited behavior or contract creates special cases.

Decision factor Inheritance Composition
Relationship Use when the subtype can honor the expectations of the base type. Use when one object needs another object’s capability without being that object’s subtype.
Interface coupling The subclass is coupled to the base interface and its behavior. The containing class exposes or delegates only the operations it needs.
Dispatch Overrides and the method resolution order affect which implementation runs. Calls go through the stored helper object, making the delegation explicit.
Independent testing Tests must account for inherited behavior and base-class assumptions. The helper can be tested or replaced independently of the containing class.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How does super() work with multiple inheritance?

In multiple inheritance, Python follows a method resolution order (MRO). super() means continue lookup after the current class in the receiver’s MRO; it does not simply mean “call my direct parent.” This lets cooperating methods pass control through a hierarchy, including a diamond-shaped one.

Make cooperative methods consistent

For methods designed to cooperate, each participant should use super() and have a compatible signature. A direct-parent call can bypass another class in the MRO or cause work to happen twice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
class Root:
    def run(self):
        print("Root")

class Left(Root):
    def run(self):
        print("Left")
        super().run()

class Right(Root):
    def run(self):
        print("Right")
        super().run()

class Combined(Left, Right):
    def run(self):
        print("Combined")
        super().run()

print(Combined.__mro__)
Combined().run()

The MRO for Combined is Combined, Left, Right, Root, object. The calls proceed in that order because each implementation continues lookup with super(). To see the actual order for a class, inspect Class.__mro__, or use type(instance).__mro__ for an object. The Python Tutorial’s explanation of multiple inheritance and cooperative super() is in its multiple-inheritance section.

Does Python have private instance variables?

Python does not provide strictly inaccessible private instance variables. A leading underscore, as in _cache, signals that an attribute is non-public by convention. Double-leading underscores, as in __cache, trigger name mangling: Python changes the stored name to reduce accidental clashes with names in subclasses. Name mangling is not access control and does not make the value impossible to reach. Use it mainly when avoiding some subclass name conflicts; use a single leading underscore to mark internal details.

The Python Tutorial covers these privacy conventions in its private variables section.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.