Python 中的实例变量与类变量 [英] Instance variables vs. class variables in Python

查看:32
本文介绍了Python 中的实例变量与类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Python 类,在运行时我只需要一个实例,因此每个类而不是每个实例只拥有一次属性就足够了.如果有多个实例(不会发生),则所有实例都应具有相同的配置.我想知道以下哪个选项会更好或更惯用"Python.

I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there would be more than one instance (which won't happen), all instance should have the same configuration. I wonder which of the following options would be better or more "idiomatic" Python.

类变量:

class MyController(Controller):

  path = "something/"
  children = [AController, BController]

  def action(self, request):
    pass

实例变量:

class MyController(Controller):

  def __init__(self):
    self.path = "something/"
    self.children = [AController, BController]

  def action(self, request):
    pass

推荐答案

如果无论如何你只有一个实例,最好将所有变量都设置为每个实例,因为它们会被访问(一点点)更快(少一个)由于从类到实例的继承"而导致的查找"级别),并且没有任何缺点可以抵消这一小优势.

If you have only one instance anyway, it's best to make all variables per-instance, simply because they will be accessed (a little bit) faster (one less level of "lookup" due to the "inheritance" from class to instance), and there are no downsides to weigh against this small advantage.

这篇关于Python 中的实例变量与类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆