gpt4 book ai didi

python - 函数在子类中不被覆盖

转载 作者:行者123 更新时间:2023-11-28 20:46:28 28 4
gpt4 key购买 nike

我有这两个类:

class Shape(object):
def __init__(self, start_point, *args):
self.vertices = []
self.__make_vertices(start_point, *args)

def __make_vertices(self, start_point, *args):
print "Not Implemented: __make_vertices"

def __getitem__(self, *args):
return self.vertices.__getitem__(*args)

class Cube(Shape):
def __init__(self, start_point, side_length):
Shape.__init__(self, start_point, side_length)

def __make_vertices(self, start_point, side_length):
append = self.vertices.append
start_point = Vector(*(start_point))
i, j, k = side_length*I, side_length*J, side_length*K
append(start_point)
append(self.vertices[-1] - k)
append(self.vertices[-1] - j)
append(self.vertices[-1] + k)
append(self.vertices[-1] - i)
append(self.vertices[-1] - k)
append(self.vertices[-1] + j)
append(self.vertices[-1] + k)
print self.vertices

当我创建一个新的 Cube 时,我希望我在 Cube 类中定义的 __make_vertices 函数会被调用,但我却一直收到消息说 Shape classes __make_vertices 函数打印出来。我误会了什么?

最佳答案

你错过了name mangling :

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

换句话说,当您特别希望子类覆盖它们,而是提供它们自己的私有(private)版本时,您应该只使用以两个下划线开头的属性/方法名称。这种情况很少见,因此通常您根本不需要使用双下划线名称。

关于python - 函数在子类中不被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20732325/

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