为什么在创建对象之前调用__init__?

时间:2013-06-08 13:18:14

标签: python init

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()。

1 个答案:

答案 0 :(得分: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()