[英]understanding python class variable
Why do we have template_name = None as class variable here?(from django source code) 为什么我们在这里有template_name = None作为类变量?(来自Django源代码)
It's because if self.template_name is None, would raise an error? 这是因为如果self.template_name为None,会引发错误吗?
(self.template_name would look for instance variable and if it's not there, would return the class variable) (self.template_name将查找实例变量,如果不存在,将返回类变量)
If so, wouldn't it be better to have def __init__(self): self.template_name = None ?
如果是这样,那么使用
def __init__(self): self.template_name = None ?
会更好def __init__(self): self.template_name = None ?
class TemplateResponseMixin(object):
"""
A mixin that can be used to render a template.
"""
template_name = None
response_class = TemplateResponse
def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template rendered with the given context.
"""
return self.response_class(
request = self.request,
template = self.get_template_names(),
context = context,
**response_kwargs
)
def get_template_names(self):
"""
Returns a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
"""
if self.template_name is None:
raise ImproperlyConfigured(
"TemplateResponseMixin requires either a definition of "
"'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
TemplateResponseMixin is a mixin which is not using an init, to make it easier to use in a mutiple inheritence. TemplateResponseMixin是一个不使用init的mixin,以使其更易于在多继承中使用。 It does not need its own state, so it does not need a constructor.
它不需要自己的状态,因此不需要构造函数。 This also makes the inheritence easier because you don' t need to call a constructor on it in your subclass.
这也使继承更加容易,因为您无需在子类中对其调用构造函数。
The template_name is set as a class instance obviously because there is no constructor. 显然因为没有构造函数,所以将template_name设置为类实例。 It implies that it should be set from the subclass.
这意味着应该从子类中设置它。 Also, changing the value of it will affect all future instances of that mixin.
同样,更改它的值将影响该mixin的所有将来实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.