【问题标题】:Code Design when Dealing with Large Numbers of Instance Attributes in Python在 Python 中处理大量实例属性时的代码设计
【发布时间】: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 instance-variables readability code-readability


【解决方案1】:

这正是解包参数的用途。在这种情况下,由于您传递的是keyword arguments,您可以使用**kwargs

def __init__(self,**kwargs):
    # do stuff with kwargs[X] which X is the name of your argument

对于您的positional arguments,您可以使用一个星形前缀*args,它可以让您将任意参数列表传递给函数:

def __init__(self,*args):
      # then you can loop over the args in order to achieve to arguments

【讨论】:

  • 有没有办法为未知数量的变量定义默认值?谢谢!
  • @AustinGarrett 如果他们不知道你怎么知道默认值应该是什么?
  • @AustinGarrett 你能用一个例子来描述你的问题吗?您可以使用新信息更新您的问题。
  • 我想出了一个解决方案;我只是定义了一个名为“default_params”的类字典,然后在 __init__ 我使用 for var in default_params: self.var = kwargs.pop('var',default_params[var])
猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2017-12-01
  • 1970-01-01
  • 2021-05-16
  • 2020-02-19
  • 1970-01-01
相关资源
最近更新 更多