运行时更换方法而不更新私有属性

use*_*851 6 python python-3.x

我了解了如何通过浏览这些链接在Python中运行时替换方法.[ Link1,Link2Link3 ].

当我替换A类的"update_private_variable"方法时,它被替换但不更新私有变量.

import types

class A:
    def __init__(self):
        self.__private_variable = None
        self.public_variable = None

    def 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_variable

class B:
    def __init__(self):
        self.__private_variable = None
        self.public_variable = None

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

    def update_public_variable(self):
        self.public_variable = "Updated in B"
Run Code Online (Sandbox Code Playgroud)

在没有替换的情况下调用方法:

a_instance  = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"   
Run Code Online (Sandbox Code Playgroud)

更换后调用方法时:

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
Run Code Online (Sandbox Code Playgroud)

而替换和调用更新公共变量的方法,工作正常

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'
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以在运行时替换实例的方法,以便通过调用替换的方法来更新私有属性?

Eth*_*man 1

名称修饰背后的想法是保护基类变量不被子类弄乱;换句话说,如果您认为子类有充分的理由修改这些相同的变量,则不应使用它。

话虽如此,如果你已经沿着这条路走下去并且现在无法(或不愿意)改变它,你仍然可以过去,但它会是丑陋和脆弱的:

class B:

    def update_private_variable(self):
        self._A__private_variable = "Updated in B"
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您必须在名称损坏的变量前加上前缀,_以及该变量被损坏的类的名称。一些后果:

  • 如果更改类的名称,则必须更改对该类的所有引用中的名称
  • 你不能轻易地使用相同的update_private_variable方法(因为你必须以某种方式指示目标类......我想你可以将目标类传递给该方法,但这只是更丑陋)