Method replacement at runtime not updating Private attributes

2024/5/20 18:59:29

I understood how to replace methods at run time in Python by going through these links.[ Link1 , Link2 , & Link3].

When I replaced a "update_private_variable" method of class A, its getting replaced but its not updating the private variable.

import typesclass A:def __init__(self):self.__private_variable = Noneself.public_variable = Nonedef update_private_variable(self):self.__private_variable = "Updated in A"def update_public_variable(self):self.public_variable = "Updated in A"def get_private_variable(self):return self.__private_variableclass B:def __init__(self):self.__private_variable = Noneself.public_variable = Nonedef update_private_variable(self):self.__private_variable = "Updated in B"def update_public_variable(self):self.public_variable = "Updated in B"

When calling the method without replacement:

a_instance  = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"   

When calling the method after replacement:

a_instance  = A()
a_instance.update_private_variable =  types.MethodType(B.update_private_variable, a_instance)
a_instance.update_private_variable()
print(a_instance.get_private_variable()) 
#prints None

Whereas replacing and calling a method which updates public variable, works fine

a_instance  = A()
a_instance.update_public_variable = types.MethodType(B.update_public_variable, a_instance)
a_instance.update_public_variable()
print(a_instance.public_variable) 
#prints 'Updated in B'

Is there any other way to replace method of an instance at runtime, so that private attributes gets updated by invoking replaced method?

Answer

The idea behind name mangling is to protect base-class variables from being messed with by sub-classes; in other words, you shouldn't use it if you think sub-classes will have a good reason to modify those same variables.

Having said that, if you are already well down that path and are unable (or unwilling) to change it now, you can still get by, but it will be ugly and brittle:

class B:def update_private_variable(self):self._A__private_variable = "Updated in B"

As you can see, you have to prefix the name-mangled variable with an _ and the name of the class the variable is mangled in. Some of the consequences:

  • if you change the name of the class, you must change the name in all references to it
  • you cannot easily use the same update_private_variable method (since you have to somehow indicate the target class... I suppose you could pass the target class in to the method, but that's just more ugliness)
https://en.xdnf.cn/q/73293.html

Related Q&A

sys.path and sys.executable is incorrect in jupyter, but no applied fix is working

Ive configured jupyter to be used from a remote computer and set a password to it while initial anaconda setup. Then after fixing this issue, I am trapped in another one. sys.path and sys.executable is…

How to multicolour text with ScrolledText widget?

from tkinter import * from tkinter.scrolledtext import ScrolledTextwindow= Tk() window.geometry(970x45) box = ScrolledText(window, width=70, height=7).pack() box.insert(END, "Ehila") #this in…

Binding Return to button is not working as expected

I bound the event <Return> to a Button, thinking that this would cause the command to be run after hitting Enter:Button(self.f, text="Print", command=self.Printer).pack(side=RIGHT, padx…

ZMQ Pub-Sub Program Failure When Losing Network Connectivity

I have a simple pub-sub setup on a mid-sized network, using ZMQ 2.1. Although some subscribers are using C# bindings, others are using Python bindings, and the issue Im having is the same for either.I…

replacing html tags with BeautifulSoup

Im currently reformatting some HTML pages with BeautifulSoup, and I ran into bit of a problem.My problem is that the original HTML has things like this:<li><p>stff</p></li>and &…

LightGBM: train() vs update() vs refit()

Im implementing LightGBM (Python) into a continuous learning pipeline. My goal is to train an initial model and update the model (e.g. every day) with newly available data. Most examples load an alread…

GTK: create a colored regular button

How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesnt do anything. Im able to add an EventBox to the button, and add a label to that, and then change its color…

How to Normalize similarity measures from Wordnet

I am trying to calculate semantic similarity between two words. I am using Wordnet-based similarity measures i.e Resnik measure(RES), Lin measure(LIN), Jiang and Conrath measure(JNC) and Banerjee and P…

How to open chrome developer console using Selenium in Python?

I am trying to open developer console in chrome using selenium webdriver. I am doingfrom selenium import webdriverfrom selenium.webdriver.common import action_chains, keys...browser = webdriver.Chrome(…

How to enable an allow-insecure-localhost flag in Chrome from selenium?

I want to enable "allow-insecure-localhost" flag from selenium. How I can do it?selenium: 3.12.0, Python:3.6.5Chrome driver creation code:def create_driver():options = Options()if sys.plat…