首页 > 解决方案 > 具有许多属性的类的构造函数

问题描述

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

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

我想问一下是否推荐这种方法,以及是否有一种通用方法可以为具有许多属性的类创建构造函数。

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

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

标签: pythonconstructor

解决方案


这不是性能或“使用频率”的问题。是接口的问题。

你有一个类,它提供了创建对象的接口。有人(甚至你自己)会用它来做某事。问题是,这个属性是对象构造函数的一部分吗?在创建对象时提供此值是否有意义?让用户能够从对象外部设置它是否有意义?

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

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

这样你可以省略这两个参数,你可以在需要时提供它。但好消息是您向用户提示您可以在创建过程中设置什么。


推荐阅读