-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 ?

gag123
  • 357
  • 1
  • 2
  • 8

1 Answers1

0

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)
év3v
  • 26
  • 4
  • Even with the `.name` attribute, it's still the _same class_. This just creates _different instances_ of it. – Gino Mempin Apr 25 '22 at 07:08
  • 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? – év3v Apr 25 '22 at 08:19