类但不是实例构造函数

时间:2016-04-20 08:10:19

标签: python

有一个类似的问题,但它没有明确回答我的问题: 有没有办法有一个init /构造函数,它将在所有类实例中自动调用ONCE,以便初始化类变量?

class A:
  _config = None
#load the config once for all instances
  @classmethod
  def contstructor(cls):
    cls._config = configparser.ConfigParser()
    cls._config.read("config_for_A.ini")

2 个答案:

答案 0 :(得分:3)

这称为" Orcish Maneuver"。它确实假设"缓存"可以评估为布尔值。

class A:
  _config = False
#load the config once for all instances
  @classmethod
  def contstructor(cls):
    cls._config = configparser.ConfigParser()
    cls._config.read("config_for_A.ini")

  def __init__(self):
      self._config = self._config or self.contstructor()

hay = A()
bee = A()
sea = A()

答案 1 :(得分:2)

类构造函数没有神奇的方法,但Python在解析类时执行不属于方法的类定义中的所有代码。因此,您可以直接在那里执行操作和分配,也可以从那里调用类的自定义方法作为类构造函数。

print("Now defining class 'A'...")

class A:

    # define any initialization method here, name is irrelevant:
    def __my_class_constructor():  
        print("--> class initialized!")

    # this is the normal constructor, just to compare:
    def __init__(self):
        print("--> instance created!")

    # do whatever you want to initialize the class (e.g. call our method from above)
    __my_class_constructor()  

print("Now creating an instance object 'a' of class 'A'...")

a = A()

输出将是:

Now defining class 'A'...
--> class initialized!
Now creating an instance object 'a' of class 'A'...
--> instance created!

See this code running on ideone.com