-1

I am new in Python before I have only Java experience , In python I need to invoked parameter constructor while I have many class and class name identifies on runtime so I need to create that class Object with constructor and as well method. with static it is working fine. for java I can use class.forName(class_name). I tried with importlib, string to class but did not work.

Excample:

class A
  def _init_(self,name):
      self.name = name
  def some_method(self):
      print('method print',self.name)

Expectation: want to achieve-

instance = A('instance A')
instance.some_method()

in the above code class A will be identified on Run time and similar many class we have and above code I need to implement dynamically, how can achieve this.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • you want to get class A from string `"A"` that is what you mean ? – azro Mar 27 '22 at 14:33
  • 1
    `A` in Python is an object just like any other, there is less separation between classes and objects. You can assign it to a variable, store it as a value in a dictionary, etc. If you need to find a global variable (which `A` is), you can go `globals()['A']` – yeputons Mar 27 '22 at 14:33
  • yes @azro , I have string "A". and need to create a class "A" object constructor. and method – prabhakar srivastava Mar 27 '22 at 14:36
  • Hi @yeputons, I have more than 200 class and I can not store all classes in variable if not required. i need to create this class on demand , on run time I have the class name in string which need to be invoked. – prabhakar srivastava Mar 27 '22 at 14:38
  • It's not really clear what exactly you are asking. You say you tried something "but did not work" – what did you try and in how far did it not work? The "Example" as shown has several blunders – at least a syntax error and a misspelled special method – are you asking about these? The "Expectation" would work assuming the obvious errors in the Example were fixed – what is missing from your attempt to reach the Expectation? What *else* do you get? – MisterMiyagi Mar 27 '22 at 14:39
  • "I can not store all classes in variable if not required" Why not? Where *else* are they stored? – MisterMiyagi Mar 27 '22 at 14:40
  • Hi @MisterMiyagi, check for this article- https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object similar problem but the solution is to store all classes in variable – prabhakar srivastava Mar 27 '22 at 14:41
  • @prabhakarsrivastava I don't understand what you mean by "solution is to store all classes in variable". A ``class`` statement automatically "stores" the class in a variable. How *else* would your classes be stored? – MisterMiyagi Mar 27 '22 at 14:43
  • @MisterMiyagi, on the same page solution number 5 or 6, have if you search- food_types.held a separate class creates and store all class in it then store and use as per requirement. storing classes I am only concern about it. – prabhakar srivastava Mar 27 '22 at 14:51
  • 1
    Does this answer your question? [Does python have an equivalent to Java Class.forName()?](https://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname) – Mahmudul Hasan Mar 27 '22 at 14:59
  • "on the same page solution number 5 or 6" Answer order is not fixed, so just giving a vague ordinal is not clear. Regardless, there are many more solutions that *don't* add extra data structures - what about those doesn't work for you? You still haven't clarified how the classes are stored initially, either. I think an actual [MRE] might be needed here. – MisterMiyagi Mar 27 '22 at 15:07
  • @MisterMiyag, I tried- solution1- import sys def str_to_class(classname): return getattr(sys.modules[__name__], classname) solution2- globals()[class_name] solution3- import importlib def class_for_name(module_name, class_name): # load the module, will raise ImportError if module cannot be loaded m = importlib.import_module(module_name) # get the class, will raise AttributeError if class cannot be found c = getattr(m, class_name) return c loaded_class = class_for_name('foo.bar', 'Baz') – prabhakar srivastava Mar 27 '22 at 15:17

1 Answers1

0

If classes are in another file, use getattr

import module_with_my_classes

x = getattr(module_with_my_classes, 'A')

If you are in the file as the class definitions, use globals

x = globals()['A']
# x is a A instance
azro
  • 53,056
  • 7
  • 34
  • 70