Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize classes (not instances) in Python?

I want to merge constraints from the current and inherited classes only once a class is loaded (not per object!).

class Domain(Validatable):

    constraints = {...}

To do this I defined a method _initialize_class_not_instance that should be called once for each class:

class Validatable:

    @classmethod
    def _initialize_class_not_instance(cls):
        # merge constraints from derived class and base classes
        pass

    __class__._initialize_class_not_instance() # doesn't work
    # Validatable._merge_constraints() # doesn't work too

The problem is that __class__ doesn't exist in this context and Validatable is not defined too. But I want to avoid, that the user of my API has to call the initialize method explicitely or has to use an additional class decorator.

Any ideas how to initialize the class?

like image 260
deamon Avatar asked May 31 '11 06:05

deamon


People also ask

How do you initiate a class in Python?

Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines. The return value will be the newly created object.

Can we call class method without creating instance Python?

We can also make class methods that can be called without having an instance. The method is then similar to a plain Python function, except that it is contained inside a class and the method name must be prefixed by the classname. Such methods are known as static methods.

What does __ init __ do in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

Can I create a class without init?

We can create a class without any constructor definition. In this case, the superclass constructor is called to initialize the instance of the class. The object class is the base of all the classes in Python.


1 Answers

Use a metaclass.

class MetaClass(type):
  def __init__(cls, name, bases, d):
    type.__init__(cls, name, bases, d)
    cls.foo = 42

class MyClass(object):
  __metaclass__ = MetaClass

print MyClass.foo
like image 116
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 13:09

Ignacio Vazquez-Abrams