问题描述
我偶然发现了 mangling - 我在类函数名称中放置了两个下划线而不是一个 - 但我发现它非常有用。例如,我有各种对象需要在它们之间进行一些空中交通控制,以便我可以使用相同的函数调用它们的父对象,即 parentobject.__remove()
。使用 parentobject._remove_myclass()
没什么不同,但我有点喜欢 mangling!
Mangling 似乎旨在保护父类对象不被覆盖,所以利用这一点 a) “pythonic”,更重要的是 b) 可靠/一个好主意?
class myClass():
def __mc_func(self):
print ('Hello!')
def _yetAnotherClass__mc_func(self):
print ('Mangled from yetAnotherClass!')
def new_otherClass(self):
return otherClass(self)
def new_yetAnotherClass(self):
return yetAnotherClass(self)
class otherClass():
def __init__(self,myClass_instance):
self.mci = myClass_instance
def func(self):
self.mci.__mc_func()
class yetAnotherClass():
def __init__(self,myClass_instance):
self.mci = myClass_instance
def func(self):
self.mci.__mc_func()
g = myClass()
h = g.new_otherClass()
try:
h.func()
except AttributeError as e:
print (e)
#'myClass' object has no attribute '_otherClass__mc_func'
j = g.new_yetAnotherClass()
j.func()
#Mangled from yetAnotherClass!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)