小编典典

Python中的实例变量与类变量

python

我有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

阅读 439

收藏
2020-02-15

共1个答案

小编典典

我有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
2020-02-15