Is this in OOP Python to initialize a class from the module that it contained when importing

I am using Python 2.7

I would like to know if there is OOP in Python to add code at the module level to initialize the class contained in the module.

class DoSomething(object):

    foo = 0
    bar = 0

    @classmethod
    def set_all_to_five(cls):
        cls.bar = 5
        cls.foo = 5

    @classmethod
    def set_all_to_ten(cls):
        cls.bar = 10
        cls.foo = 10


#Module level code - runs on import of the class DoSomething
DoSomething.set_all_to_five()

Conclusion:

>>> from productX.moduleY import DoSomething
>>> print DoSomething.bar
5

The class contains only @classmethod methods, so I can call them without having to instantiate the class.

Module Level code DoSomething.set_all_to_5()Initializes class level properties when importing a module.

+4
source share
1 answer

[It it] OK to add module level code to initialize the class contained in the module?

, . , "dynamic" , Python : . , , , DoSomething, - "" .

, , , , "monkeypatch" , .

:

class DoSomethingMeta(type):

    def __init__(self, name, bases, attrs):
        super(DoSomethingMeta, self).__init__(name, bases, attrs)
        self.set_all_to_five()


class DoSomething(object):

    __metaclass__ = DoSomethingMeta  # for Python3, pass metaclass kwarg instead

    foo = 0
    bar = 0

    @classmethod
    def set_all_to_five(cls):
        cls.bar = 5
        cls.foo = 5

    @classmethod
    def set_all_to_ten(cls):
        cls.bar = 10
        cls.foo = 10

, , :

def mydecorator(cls):
    cls.set_all_to_five()
    return cls

@mydecorator
class DoSomething(object):
    ....
+1

Source: https://habr.com/ru/post/1695659/


All Articles