在 class 中访问私有方法会给出一个名称错误,指出它未定义

Accessing a private method within a class is giving a name error saying it is not defined

我正在使用此方法创建一个 class,该方法根据坐标计算给定区域的质心。这是my code so far. And I'm having this error in jupyter notebook : NameError: name '_Lot__getCentroid' is not defined. What am I doing wrong? I'm trying to just follow this UML given to me. Should I move the method getCentroid first before the initialization? I'm not sure that's customary with classes but I'm new to it so I don't know.

您的代码无法运行的原因有两个:

  1. self.centroid = __getCentroid() 仅当 __getCentroid() 函数在 class 之外声明时才有效。如果它在 class 内,你应该调用 self.__getCentroid()
  2. __getCentroid() 是静态方法,无法访问 class 或实例属性。所以您无权访问 self.*something*。如果你使用IDE这样的Pycharm,它会告诉你错误。

多读一点关于 classes 的内容,它们的属性和方法在 python :)