当name前面有双下划线时,为什么传递关键字/命名参数会产生错误?

2024-09-22 10:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在运行一个交易算法时,我遇到了以下问题,我试图用以下方式重现:

假设我有一个名为algo1.py的算法和另一个名为algo2.py的算法

这是algo2.py

class mathOperations():

    def __init__(self):
        self.value = 0

    def sum(self, __a = 0, __b = 0):
        return (__a + __b)

这里是algo1.py

from algo2 import mathOperations


math = mathOperations()
print(math.sum(__a = 56, __b = 44))

运行algo1.py时,会收到以下消息:

Traceback (most recent call last):
  File "algo1.py", line 5, in <module>
    print(math.sum(__a = 56, __b = 67))
TypeError: sum() got an unexpected keyword argument '__a'

但是,在两种算法中,当我从命名参数的前面删除'\'或两个下划线时,这个错误就消失了。有人能解释一下为什么吗


Tags: pyself算法initdef方式交易math
1条回答
网友
1楼 · 发布于 2024-09-22 10:26:46

请参阅有关name mangling的文档:

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. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

这就解释了为什么。教程here(TL;DR:这是一种避免名称与子类定义的名称冲突的方法

解决方法很简单:在定义方法的参数时,不要使用带有两个前导下划线的名称

相关问题 更多 >