gpt4 book ai didi

python - 为了良好的风格,我应该在 Python 中在方法之前定义内部类,反之亦然吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:55 26 4
gpt4 key购买 nike

我读了PEP 8: Style Guide for Python code , 但我找不到任何关于我应该在类中定义内部类或方法的顺序。

例如,我应该怎么做

class CustomClass(BaseClass):
class Meta:
foo = self.bar

def foo_bar(self):
return False

bar = 1

class CustomClass(BaseClass):
def foo_bar(self):
return False

class Meta:
foo = self.bar

bar = 1

?

编辑:这是一个 Django 源代码。他们实际上定义了字段,然后是内部类,然后是方法:

class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)

objects = LogEntryManager()

class Meta:
verbose_name = _('log entry')
verbose_name_plural = _('log entries')
db_table = 'django_admin_log'
ordering = ('-action_time',)

def __repr__(self):
return smart_unicode(self.action_time)

def __unicode__(self):
if self.action_flag == ADDITION:
return _('Added "%(object)s".') % {'object': self.object_repr}
elif self.action_flag == CHANGE:
return _('Changed "%(object)s" - %(changes)s') % {'object': self.object_repr, 'changes': self.change_message}
elif self.action_flag == DELETION:
return _('Deleted "%(object)s."') % {'object': self.object_repr}

return _('LogEntry Object')

def is_addition(self):
return self.action_flag == ADDITION

def is_change(self):
return self.action_flag == CHANGE

def is_deletion(self):
return self.action_flag == DELETION

def get_edited_object(self):
"Returns the edited object represented by this log entry"
return self.content_type.get_object_for_this_type(pk=self.object_id)

def get_admin_url(self):
"""
Returns the admin URL to edit the object represented by this log entry.
This is relative to the Django admin index page.
"""
if self.content_type and self.object_id:
return mark_safe(u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))
return None

最佳答案

普遍接受的做法是定义字段,然后是内部类,然后是方法。

关于python - 为了良好的风格,我应该在 Python 中在方法之前定义内部类,反之亦然吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10144024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com