我有Python类,运行时只需要一个实例,因此每个类只需要属性一次而不是每个实例都有。如果有多个实例(这不会发生),则所有实例应具有相同的配置。我想知道以下哪种选项更好或更符合"惯用的"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
python -mtimeit
轻松自己制作它们。但是,我刚在Python3.4中完成了这项工作,我注意到访问int
类变量实际上比在我的旧工作站上访问相同的实例变量要快大约5到11纳秒——不确定是什么代码路径导致了这种情况。 - Alex Martelli