gpt4 book ai didi

python - 'exec' 不适用于私有(private)方法 Python

转载 作者:行者123 更新时间:2023-11-30 22:43:57 25 4
gpt4 key购买 nike

我知道你们中的大多数人都认为不应该使用 exec,但我有一些问题。

这是一个最小的例子,它有效:

class A:
def __init__(self):
exec('self.a = self.funct()')
def funct(self):
return 1
def ret(self):
return self.a
> obj = A()
> obj.ret()
1

但是,当我这样做时:

class A:
def __init__(self):
exec('self.a = self.__funct()')
def __funct(self):
return 1
def ret(self):
return self.a
> obj = A()
AttributeError: 'A' has no attribute '__funct'

有人知道为什么会出现这种差异吗?

最佳答案

__name 名称是类私有(private);这些名称在编译时带有另一个下划线和类名作为前缀。目的是防止名称与子类中使用的名称发生意外冲突。这些名称​​不对于外部调用者来说是私有(private)的。

引用Reserved classes of identifiers section :

__*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes.

Identifiers (Names) section :

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used.

在您的情况下发生的情况是 exec() 推迟编译,有效地单独编译该调用。类上下文消失了,因此不会发生任何损坏。

因此,您需要手动应用自动前缀:

exec('self.a = self._A__funct()')

如果您使用的是 Python 3,则可以使用 __class__ 闭包 normally available for the super() function访问当前方法定义的类名:

exec('self.a = self._{0.__name__}__funct()'.format(__class__))

现在,除非您实际上计划在第三方代码中广泛子类化您的类,而不必担心与内部实现细节意外冲突,否则您根本不应该使用双下划线名称。坚持使用单下划线名称。

关于python - 'exec' 不适用于私有(private)方法 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41637600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com