在 exec() python 中调用私有 class 函数
call private class function in exec() python
我遇到了意外问题。这是简化的代码:
class test():
def __init__(self,name):
self.name = name
def __private(self):
print(self.name)
def public(self):
exec("self.__private()")
obj = test('John')
obj.public()
有谁知道如何在不删除 exec 语句的情况下使这段代码正常工作?
以两个下划线开头且不以两个下划线结尾的属性名称受 name mangling.
约束
当你这样做时
def __private(self):
print(self.name)
在 class 定义中,您实际上创建了一个名为 _<ClassName>__private
的方法。
您仍然可以在 class 正文中以 __private
的形式正常访问它(使用适当的限定符,例如 self
,如果适用),但为了通过exec
或 eval
,或在 class 正文之外,您必须使用其全名:
def public(self):
exec('self._test__private()')
我遇到了意外问题。这是简化的代码:
class test():
def __init__(self,name):
self.name = name
def __private(self):
print(self.name)
def public(self):
exec("self.__private()")
obj = test('John')
obj.public()
有谁知道如何在不删除 exec 语句的情况下使这段代码正常工作?
以两个下划线开头且不以两个下划线结尾的属性名称受 name mangling.
约束当你这样做时
def __private(self):
print(self.name)
在 class 定义中,您实际上创建了一个名为 _<ClassName>__private
的方法。
您仍然可以在 class 正文中以 __private
的形式正常访问它(使用适当的限定符,例如 self
,如果适用),但为了通过exec
或 eval
,或在 class 正文之外,您必须使用其全名:
def public(self):
exec('self._test__private()')