Python class changer

I need a class declaration of the runtime class from the database.

Some class needs to redefine the field and re-declare.

models.py

  class Staff (object):
     name = StringField (verbose_name = "Full name")
     age = IntegerField (verbose_name = "Age")

utils.py

  def class_changer (class_path, field_key, new_Field):
     pass
     ?????? 
>>> class_changer("models.Staff", "gender", BooleanField()) # Add new field to Staff >>> class_changer("models.Country", "name", StringField()) # Add new class with name field >>> class_changer("models.Staff", "country", ForeignKey("Country")) # Add new field to Staff 

result

  class Staff (object):
     name = StringField (verbose_name = "Full name")
     age = IntegerField (verbose_name = "Age")
     gender = BooleanField ()
     country = ForeignKey ("Country")

 class Country (object):
     name = StringField ()

How to implement class_changer?

+4
source share
2 answers

for this you need a better architecture, but as an initial solution you can try this,

 In [12]: class a1(object): ...: pass In [13]: def class_changer(cls_path, attr, val): ....: try: ....: obj = eval(cls_path) ....: setattr(obj, attr, val) ....: except: ....: raise ....: In [14]: def getGender(self): ...: return True In [15]: class_changer('a1','getGender', getGender) In [16]: a1().getGender() Out[16]: True 
+4
source

First, add new attributes to the class:

 >>> class_changer("models.Staff", "gender", BooleanField()) # Add new field to Staff >>> class_changer("models.Staff", "country", ForeignKey("Country")) # Add new field to Staff 

For these two, simply click Staff directly:

 models.Staff.gender = BooleanField() models.Staff.country = ForeignKey("Country") 

Or make it general:

 def add_to_class(cls, name, attr): setattr(cls, name, attr) add_to_class(models.Staff, "gender", BooleanField()) add_to_class(models.Staff, "country", ForeignKey("Country")) 

Secondly, creating a new class:

 >>> class_changer("models.Country", "name", StringField()) # Add new class with name field 

You can create a class in a function and then assign it to a module:

 def new_class(mod, name): class New(object): pass setattr(mod, name, New) new_class(test, "Country") add_to_class(test, "Country", StringField()) 

I'm not sure if you want to combine new_class and add_to_class , but I suppose you could do:

 def create_if_needed_and_add_to_class(mod, clsname, attrname, value): if clsname not in dir(mod): new_class(mod, clsname) add_to_class(mod, attrname, value) 

and then finally for your class_changer :

 def class_changer(mod_clsname_string, attrname, value): modname, clsname = '.'.split(mod_clsname_string) create_if_needed_and_add_to_class(globals()[modname], clsname, attrname, value) 

Edit: fixed class_changer to use locals() to search for a module name, since it is a string, not a module.

Edit: oops, this should be globals() .

+1
source

All Articles