I want to cast a parental object to a child object in Python.

Because there is no way to cast a object in Python, I make a method which do new a child class and copy values from a parental object.

usage

# cast method
def cast(child_class, parental_obj):
  child_obj = child_class()
  for attr_name in parental_obj.__dict__:
    setattr(child_obj, attr_name, getattr(parental_obj, attr_name))
  return child_obj



class ParentalClass():
  parental_attr = ""

class ChildClass(ParentalClass):
  child_attr = ""

parental_object = ParentalClass()
parental_object.parental_attr = "hello"



# usage
child_object = cast(ChildClass, parental_object)
print(child_object.parental_attr)

 



I considered the way to cast a parent object by __init__ method and hope it work like below natulally...

child_object = ChildClass(parent_object)

But this is bad for two reasons.
1) We have to define __init__ method for each class.
2) We wouldn't able to use __init__ method for a original purpose. (e.g. We cannot apply it for a class which inherited a models.Model class in Django.

python - How to convert (inherit) parent to child class? - Stack Overflow



How to cast models in Django


Remove all ads