具有许多属性的类的构造方法

时间:2018-10-25 21:55:30

标签: python constructor

当您的类具有许多属性时,编写构造函数的最佳方法是什么?

例如,在一所大学的硬件中,我们获得了一段代码,在创建对象时,您必须在其中明确设置所有属性。我注意到其中一些在开始/结束时仅使用了一次。因此,我创建了一个相等的代码,在其中我为稀有属性提供一些默认值,并仅在开始/结束时在对象创建之外设置它们。

我想问一下是否建议使用这种方法,以及是否存在一种通用方法来确定如何为具有许多属性的类构造构造函数。

这是大学代码的简化版本:

class point(object):
    def __init__(self,x,y,bonus,start_point,stop_point):
        self.x = x
        self.y = y
        self.bonus = bonus
        self.start_point = start_point
        self.stop_point = stop_point

        #some more attributes


if __name__ == '__main__':

    #some code here

    p = point(1,1,100,False,False)

    #some code here

我的版本:

class point(object):
    def __init__(self,x,y,bonus):
        self.x = x
        self.y = y
        self.bonus = bonus
        self.start_point = False
        self.stop_point = False

        #some more attributes


if __name__ == '__main__':

    #some code here

    p = point(1,1,100)

    #some code here

    #start/stop points are 1 in n (n=10000) in the original code
    #so set these attributes once in the beggining/end
    p.start_point = False
    p.stop_point = True

1 个答案:

答案 0 :(得分:1)

这不是性能或使用频率的问题。这是界面问题。

您有一个类,它提供了用于创建对象的接口。有人(甚至您自己)将使用它来做某事。问题是,此属性是对象构造函数的一部分吗?在创建对象时提供此值是否有意义?赋予用户从对象外部进行设置的能力甚至有意义吗?

如果在创建时设置此属性确实有意义,但是它通常具有相同的值,请为parameter提供默认值,但不要隐式设置它,因为您仍使它们成为公共接口的一部分:

class point(object):
    def __init__(self, x, y, bonus, start_point=False, stop_point=False):
        self.x = x
        self.y = y
        self.bonus = bonus
        self.start_point = start_point
        self.stop_point = stop_point

这样,您可以忽略这两个参数,并且可以在需要时提供它。但是好消息是,您可以向用户提示在创建过程中可以设置的内容。

相关问题