python - 具有许多属性的类的构造函数
问题描述
当您有一个具有许多属性的类时,编写构造函数的最佳方法是什么?
例如,在一所大学硬件中,我们得到了一段代码,您必须在创建对象时显式设置所有属性。我注意到其中一些在开始/结束时只使用一次。因此,我创建了一个相等的代码,在其中我为不常用的属性提供了一些默认值,并仅在开始/结束时将它们设置在对象创建之外。
我想问一下是否推荐这种方法,以及是否有一种通用方法可以为具有许多属性的类创建构造函数。
这是大学代码的简化版本:
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
解决方案
这不是性能或“使用频率”的问题。是接口的问题。
你有一个类,它提供了创建对象的接口。有人(甚至你自己)会用它来做某事。问题是,这个属性是对象构造函数的一部分吗?在创建对象时提供此值是否有意义?让用户能够从对象外部设置它是否有意义?
如果在创建时设置此属性确实有意义,但它大部分具有相同的值,请为参数提供默认值,但不要隐式设置它,因为您仍然使它们成为公共接口的一部分:
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
这样你可以省略这两个参数,你可以在需要时提供它。但好消息是您向用户提示您可以在创建过程中设置什么。
推荐阅读
- javascript - 什么是返回用户数据的 instagram API
- visual-studio-code - vscode - 扩展可折叠
- javascript - 搜索数据库时出现错误,不知道如何解决
- c - 分段默认值(双指针/结构)
- c# - 如何在 Xamarin 中设置 ContentPage 的背景图像
- javascript - parseFloat 返回 NAN 甚至很难我正在解析一个数字
- java - 如何反转链表?
- r - 使用 R 将函数应用于矩阵中的每个行组合 公共连接
- apache-spark - Hadoop 通过 Hadoop 配置文件分配 Master 和 Worker 节点的工作流程是什么?
- react-native - 如何更改 React 本机应用程序 SHA1 值?