调用类内类外定义的python方法

2024-04-23 09:57:40 发布

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

import math

class Circle(object):    
    def __init__(this,x,y,rad):
        this.x=x
        this.y=y
        this.rad=rad

    def relate(circ1,circ2):
        diff=__posDiff((circ1.x,circ1.y),(circ2.x,circ2.y))
        print diff

def __posDiff(p1,p2):
    diff=math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
    return diff

尝试运行上述代码时,出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Circle.py", line 18, in relate
    diff=__posDiff((circ1.x,circ1.y),(circ2.x,circ2.y))
NameError: global name '_Circle__posDiff' is not defined

对python很陌生,不知道如何调用内部函数类。如果任何人都可以帮忙解释


Tags: indeflinediffmaththisfilep2
1条回答
网友
1楼 · 发布于 2024-04-23 09:57:40

__posDiff重命名为_posDiff(因此删除一个前导下划线)。你知道吗

在名称的开头使用双下划线,当在类定义中使用这样的名称时,Python将该名称损坏以生成类私有名称。此功能用于向不应在子类中意外重写的方法添加命名空间。你知道吗

这既适用于类中定义的方法名,也适用于任何试图使用此类名称的代码。因此,在relate方法中对__posDiff的引用被重写为_Circle__posDiff(在类名前面添加了创建名称空间的前缀),但是__posDiff函数本身没有重新命名,因为它实际上不在类内部。你知道吗

参见词汇分析文档中的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. See section Identifiers (Names).

表达式引用中链接的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.

粗体斜体强调是我的。你知道吗

相关问题 更多 >