1
class Point(object): 

    def __init__(self, x=0, y=0):
        self.__x = x
        self.__y = y
        print 'point ({x},{y}) created.'.format( x=self.__x, y=self.__y )

class Line(object):

    def __init__(self, start_point=Point(), end_point=Point()):
        print 'Line.__init__ called.'
        self.start = start_point
        self.end = end_point

def test_line():
    p1 = Point(1,1)
    p2 = Point(2,2)
    line1 = Line(p1, p2)

if __name__=='__main__':
    test_line()

当我运行这个脚本时,它给出了结果:

point (0,0) created.
point (0,0) created.
point (1,1) created.
point (2,2) created.
Line.__init__ called.

我不知道为什么在创建 line1 之前调用 Point.__init() 。

4

1 回答 1

5
def __init__(self, start_point=Point(), end_point=Point())

默认函数参数是函数本身的成员,在定义函数时创建,而不是在运行时创建。所以每个实例都Line使用相同startend

解决此问题的常用方法是默认将它们设置为None

def __init__(self, start_point=None, end_point=None):
    if start_point is None:
        self.start = Point()
    if end_point is None:
        self.end = Point()
于 2013-06-08T13:19:39.293 回答