【发布时间】:2022-10-14 19:16:46
【问题描述】:
我有办法直接访问 Python 子类中的 dundle 方法吗?
想象一下,我有以下课程:
class Parent(object):
def __init__(self, x):
self.x = x
def __add(self,y):
return self.x + y
def addition(self,y):
return self.__add(y)
class Children(Parent):
def add(self,y):
return self.__add(y)
我显然可以实例化这两个类,并在两者上都使用addition,但我不能从Children 的实例中使用add。我如何访问从Parent 类继承到Children 类的__add 方法?
p = Parent(2)
p.addition(4)
c = Children(5)
c.addition(4)
所有这些电话都有效,但下面的两个电话无效
p.__add(5) # AttributeError: 'Parent' object has no attribute '__add'
c.add(4) # AttributeError: 'Children' object has no attribute '_Children__add'
并且两者都返回缺少属性。第一个行为是预期的行为,我不想改变,但第二个行为让我感到不安,因为子类应该能够访问其父隐藏方法,不是吗?
更多细节:事实上,在我的例子中,父类正在处理数据库连接,并处理用户名和密码,并使用一些方法来检查密码__check_password,我更喜欢让“私有”。我想从不同的子类调用__check_password,稍后处理数据操作。
【问题讨论】:
-
return self._Parent__add(y)?见name mangling。
标签: python inheritance subclass private-methods