1

所以我正在用Python編寫一個程序,而且它變得相當長。正如我擴展它,我已經開始注意到,我的一些類獲得了很多屬性,並且我將它們傳遞給__init__的方式只是感覺不太理想。作爲一個例子,這裏是我在說什麼:在Python中處理大量實例屬性時的代碼設計

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) 

這顯然很凌亂,我寧願簡化我的代碼。所以我的問題是,是否有更好的方式來處理所有這些變量,而不是我做這件事的方式?

+0

這ISN特定於Python的問題,請參閱https://sourcemaking.com/refactoring/smells/long-parameter-list – jonrsharpe

回答

0

這正是解包參數所要求的。在這種情況下,因爲你逝去的keyword arguments您可以使用**kwargs

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

,併爲您的你可以用一個星形前綴*args它可以讓你傳遞任意參數列表功能:

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

有沒有辦法爲未知數量的變量定義默認值?謝謝! –

+0

@AustinGarrett如果他們不知道你怎麼知道默認值應該是什麼? – Daenyth

+0

@AustinGarrett你能用一個例子來描述你的問題嗎?你可以用新的信息更新你的問題。 – Kasramvd