-1

Is it a good coding practice to have the class name as variable. E.g

def create_class(class_name):
   class class_name:
     def __init__(self):
       do_sth....
   class_instance = class_name()
   return class_instance


for object in objects:
      res = create_class(object)

I wanted to create different classes which are present in a list like objects=[person,vehicle, location ..]. What could be other alternative way to do it ?

7
  • You should probably use dicts. Commented Apr 25, 2022 at 6:17
  • 1
    What do you mean by the name of a class as variable? Commented Apr 25, 2022 at 6:18
  • @Guy Just edited..The class name is variable. Commented Apr 25, 2022 at 6:20
  • 1
    You know you are not actually creating a dynamic class name here? regardless of what the content of the parameter is the class will still be class_name. Commented Apr 25, 2022 at 6:27
  • 1
    That's an utterly bad practice. Use dataclasses or dicts. Commented Apr 25, 2022 at 6:28

1 Answer 1

-1

class_name is a class, you can set a name property for your class, like this:

class class_name:
    def __init__(self,name):
        self.name = name
    def __str__(self):
        return str(self.name)


objects=["person","vehicle","location"]
for obj in objects:
    res = class_name(obj)
    print(res)
Sign up to request clarification or add additional context in comments.

2 Comments

Even with the .name attribute, it's still the same class. This just creates different instances of it.
yeah i know, it will be always a class_name object , he needs to code a class for each objects , attributes/properties aren't the same ( i guess ... ?). Is there a reason to create a dynamic class, if they have the same attributes why didn't make you inheritance?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.