Python中的实例变量与类变量 [英] Instance variables vs. class variables in 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 (what 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屋!