M
M
Mike Evstropov2016-01-15 16:26:49
Python
Mike Evstropov, 2016-01-15 16:26:49

Is it possible to use a string to instantiate a class in Python?

Below we have 3 classes, we need the first 2 to be inherited from Master.
Then, they must be declared after Maser, otherwise there will be an error.
But on the other hand, since in our case objects are created when they are called (using the classes property of the Master class to find the class), I would like to remove this property altogether, and create a class through the name string, which is passed when calling __getattr__.
Is it possible? Thank you!

class Test:
  a = 5

class Check:
  a = 7

class Master:
  classes	= {
    'test': Test,
    'check': Check
  }
  
  objects = {}
  
  def __getattr__(self, name):
    if name in self.objects:
      return self.objects[name]
    elif not name in self.classes:
      print('Класс не найден')
      return False
    else:
      self.objects[name]	= self.classes[name]()
      print('Класс создан')
      return self.objects[name]

master = Master()
print(master.test.a)
print(master.check.a)
# Класс создан
# 5
# Класс создан
# 7

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2016-01-15
@Aroused

>>> class Test:
  a = 5
>>> globals()['Test']()
<Test object at 0x7f73aade9cc0>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question