【发布时间】:2016-03-07 17:42:52
【问题描述】:
所以我正在用 Python 编写一个程序,而且它变得相当长。随着我的扩展,我开始注意到我的一些类获得了许多属性,并且我将它们传递给 __init__ 以一种感觉不理想的方式。例如,这就是我所说的:
class Enemy(Ship):
def __init__(self,m=20000,size=32,F=[0,0],X=[0,0],v=[0,0],a=[0,0],p=[0,0],
tau=0,theta=0,omega=0,alpha=0,I=850000,rel_X_cm=[16,16],sprites=[pygame.image.load("core_off.png"),pygame.image.load("core_on.png")],
health=0,module_type="Thruster",module_coordinates=[0,0],core_module=None,
module_orientation=0,F_max=[4000000,0],tau_max=0,
attached_modules=[],surrounding_points = [[1,0],[0,1],[-1,0],[0,-1]]):
super(Enemy,self).__init__(m,size,F,X,v,a,p,tau,theta,
omega,alpha,I,rel_X_cm,sprites,
health,module_type,module_coordinates,
core_module,module_orientation,F_max,tau_max,
attached_modules,surrounding_points)
这显然很混乱,我更愿意简化我的代码。所以我的问题是,有没有比我现在做的更好的方法来处理所有这些变量?
【问题讨论】:
-
这不是 Python 特有的问题,参见例如sourcemaking.com/refactoring/smells/long-parameter-list
标签: python instance-variables readability code-readability