我使用了Python編程語言,因爲它的設計哲學,它的偉大社區,對我來說最重要的是它的美麗語法。不過,最近我還是有點沮喪。在我試圖自定義Django的過程中,我遇到了一些代碼,我認爲語法可能更清晰。我絕不是一個經驗豐富的Python程序員,事實上,我在過去的幾個月裏一直只使用它。我會很感激你的見解和你的觀點。爲什麼Django讓Python看起來很醜?
這裏是我所遇到的一些代碼示例:
爲什麼有需要的斜線?
from django.contrib.admin.util import get_model_from_relation, \
reverse_field_path, get_limit_choices_to_from_path
這可以寫得更優雅嗎?
rel_name = other_model._meta.pk.name
self.lookup_kwarg = '%s__%s__exact' % (self.field_path, rel_name)
self.lookup_kwarg_isnull = '%s__isnull' % (self.field_path)
self.lookup_val = request.GET.get(self.lookup_kwarg, None)
self.lookup_val_isnull = request.GET.get(
self.lookup_kwarg_isnull, None)
self.lookup_choices = f.get_choices(include_blank=False)
我不明白的一件事是爲什麼後面的if語句的代碼是在單獨的行上?
def has_output(self):
if isinstance(self.field, models.related.RelatedObject) \
and self.field.field.null or hasattr(self.field, 'rel') \
and self.field.null:
extra = 1
else:
extra = 0
return len(self.lookup_choices) + extra > 1
這看起來很凌亂!
def choices(self, cl):
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
yield {'selected': self.lookup_val is None
and not self.lookup_val_isnull,
'query_string': cl.get_query_string(
{},
[self.lookup_kwarg, self.lookup_kwarg_isnull]),
'display': _('All')}
for pk_val, val in self.lookup_choices:
yield {'selected': self.lookup_val == smart_unicode(pk_val),
'query_string': cl.get_query_string(
{self.lookup_kwarg: pk_val},
[self.lookup_kwarg_isnull]),
'display': val}
if isinstance(self.field, models.related.RelatedObject) \
and self.field.field.null or hasattr(self.field, 'rel') \
and self.field.null:
yield {'selected': bool(self.lookup_val_isnull),
'query_string': cl.get_query_string(
{self.lookup_kwarg_isnull: 'True'},
[self.lookup_kwarg]),
'display': EMPTY_CHANGELIST_VALUE}
請不要誤會我的意思,我不是對得住的Django的許多貢獻者,相反我真的很佩服他們,我很感激。我明白,也許這是我對Python本身缺乏經驗,或者使得語法看起來不清晰的代碼實際上是Python編程語言的核心功能。
只要說清楚這個問題是真誠的,我真誠地問這個問題本着學習和討論的精神。如果您沒有任何有助於貢獻的內容,請不要回復。
謝謝
所有的「 \「是否能夠繼續下一行的代碼。這是一種保持行較短的方法(例如,少於80個字符)。保持這種方式很常見,因爲您可以在同一區域看到所有代碼。現在,對於「如果」條件,我會將所有內容都包含在圓括號中,這樣就不需要在行末加「\」...... – 2011-12-31 13:42:14
@RicardoCárdenes:反斜槓不是必需的,它們實際上是不鼓勵的Python風格指南。 – 2011-12-31 13:44:47
我同意Bastien,這個代碼本來可以用很多其他語言寫得非常相似。沒有使用優雅的Python功能。 – 2011-12-31 13:46:48