I have these two classes:
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
When I make a new Cube
, I expected that the __make_vertices
function I defined in the Cube class would be called, but instead I keep getting the message that the Shape
classes __make_vertices
function prints out. What am I misunderstanding?
You are missing 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.
In other words, you should only use attribute/method names beginning with two underscores when you specifically don't want subclasses to override them, but rather to provide their own private version of them. This is rare, so usually you won't need to use double-underscore names at all.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句