Записи по тегу “объекты”.

Динамическое создание объектов

Простой трюк если вам необходимо создать объект из его названия.

Для себя я нашел простой набор функций

  1. def _get_mod(modulePath):
  2.     return __import__(modulePath, globals(), locals(), [‘*’])
  3.  
  4.  
  5. def _get_func(fullFuncName):
  6.     """Retrieve a function object from a full dotted-package name."""
  7.    
  8.     # Parse out the path, module, and function
  9.     lastDot = fullFuncName.rfind(u".")
  10.     funcName = fullFuncName[lastDot + 1:]
  11.     modPath = fullFuncName[:lastDot]
  12.    
  13.     aMod = _get_mod(modPath)
  14.     aFunc = getattr(aMod, funcName)
  15.    
  16.     # Assert that the function is a *callable* attribute.
  17.     assert callable(aFunc), u"%s is not callable." % fullFuncName
  18.    
  19.     # Return a reference to the function itself,
  20.     # not the results of the function.
  21.     return aFunc
  22.  
  23.  
  24. def _get_class(fullClassName, parentClass=None):
  25.     """Load a module and retrieve a class (NOT an instance).
  26.    
  27.    If the parentClass is supplied, className must be of parentClass
  28.    or a subclass of parentClass (or None is returned).
  29.    """
  30.     aClass = _get_func(fullClassName)
  31.    
  32.     # Assert that the class is a subclass of parentClass.
  33.     if parentClass is not None:
  34.         if not issubclass(aClass, parentClass):
  35.             raise TypeError(u"%s is not a subclass of %s" %
  36.                             (fullClassName, parentClass))
  37.    
  38.     # Return a reference to the class itself, not an instantiated object.
  39.     return aClass

После можно это использовать таким образом

  1. model_type = _get_class("example.MyView")

Далее просто создаем экземпляр нашего класса

  1. model_object = model_type()

Если надо вызвать определенный метод то достаточно воспользоваться getattr

  1. getattr(model_object, ‘mymethod’)()