2015-04-17 84 views
1

我有一個Python列表蟒蛇全局名稱沒有被定義

readonly = ['name', 'description']

,我想在幾個方法來使用。不過,我得到一個全局變量沒有定義錯誤

class EditForm(ModelForm): 
    # When editing form we want to disable multiple fields 
    # Admin users can edit existing items via admin interface 
    readonly = ['name', 'description'] 

    def __init__(self, *args, **kwargs): 
     super(EditForm, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     for ro_field in readonly: 
      if instance and instance.pk: 
       self.fields[ro_field].widget.attrs['readonly'] = True 

如何保持列表本地和能夠使用它在__init__功能和隨後的方法不重複設定各項功能列表

回答

1

當你像你這樣寫代碼

class EditForm(ModelForm): 
    # When editing form we want to disable multiple fields 
    # Admin users can edit existing items via admin interface 
    readonly = ['name', 'description'] 

    def __init__(self, *args, **kwargs): 
     super(EditForm, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     for ro_field in readonly: 
      if instance and instance.pk: 
       self.fields[ro_field].widget.attrs['readonly'] = True 

你正在創建一些你可以調用靜態變量的東西。接取它,你必須使用後續sintax

ClassName.variable 

self.variable

因此,要訪問它,只是做:聲明

readonly = ['name', 'description'] 
之間的差異

class EditForm(ModelForm): 
    # When editing form we want to disable multiple fields 
    # Admin users can edit existing items via admin interface 
    readonly = ['name', 'description'] 

    def __init__(self, *args, **kwargs): 
     super(EditForm, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     for ro_field in EditForm.readonly: 
      if instance and instance.pk: 
       self.fields[ro_field].widget.attrs['readonly'] = True 

And

self.readonly = ['name', 'description'] 

第二種情況是否意味着該屬性屬於您實例化的對象,因此每個對象都有自己的readonly列表,如果您更改它或其他內容,則必須爲每個對象更改它。

在第一種情況下,屬性屬於類,所以它在所有對象中都是相等的。

+1

您也可以使用'self.attr'訪問類的實例方法中的屬性(但如果你*分配to *'self.attr',你創建一個影射類屬性的實例屬性)。 – jonrsharpe

1

readonly在這裏是您的EditForm類的屬性。您可以訪問它或者直通類(EditForm.readonly)或 - 更好 - 直通實例本身:

class EditForm(ModelForm): 
    # When editing form we want to disable multiple fields 
    # Admin users can edit existing items via admin interface 
    readonly = ['name', 'description'] 

    def __init__(self, *args, **kwargs): 
     super(EditForm, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     if instance and instance.pk: 
      for ro_field in self.readonly: 
       self.fields[ro_field].widget.attrs['readonly'] = True 

這是更好,因爲它避免了硬編碼的類名進入方法來訪問它直通的實例,將更好的支持繼承(如果您繼承了EditForm並且想要在您的子類中覆蓋readonly)。

而且我把if instance and instance.pk測試循環之前 - 無需重新測試,如果每次迭代;)

相關問題