Dynamically implement __str__ if not implemented - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Dynamically implement __str__ if not implemented (/thread-26261.html) |
Dynamically implement __str__ if not implemented - jamesbond112 - Apr-25-2020 I am trying to write a function, strFix, that takes a class object as parameter, and checks if the class has an __str__() method , and if not will automatically add one, that prints all the member variables on one line eg: prints number of sides, list of sides and area of the triangle. However, after calling strFix(triangle) i get a triangle object returned instead of printing it?def constructor(self, arg): self.no_of_sides = arg def setSidesT(self, x, y, z): self.x = x self.y = y self.z = z self.listattr = [x, y, z] def createSubClass(self): self = type( "Triangle", # subclass name (Polygon,), # super class(es) { "listattr": [], # new attributes and functions/methods "setSides": setSidesT, "findArea": (lambda obj: (obj.x + obj.y + obj.z) / 2), "getTriangleSides": (lambda x: print(x.listattr)), }, ) return self Polygon = type( "Polygon", (object,), { "no_of_sides": 0, "__init__": constructor, "getSides": (lambda obj: obj.no_of_sides), }, ) def Tprinter(self): return str(self.no_of_sides, self.getTriangleSides, self.findArea) def strFix(self): if not type(self).__dict__.get("__str__"): setattr(self, "__str__", Tprinter) triangle = createSubClass(Polygon)(3) triangle.setSides(4, 5, 6) triangle.getTriangleSides() strFix(triangle) print(triangle.findArea()) print(triangle) RE: Dynamically implement __str__ if not implemented - Larz60+ - Apr-25-2020 for the type of function you are describing, you should use __repr__ RE: Dynamically implement __str__ if not implemented - deanhystad - Apr-25-2020 You were setting attributes in the object, not the class. I also had to make a few changes to Tprinter. def Tprinter(self): return f'{self.no_of_sides} {self.getTriangleSides()} {self.findArea()}' def strFix(self): cls = type(self) if not cls.__dict__.get("__str__"): setattr(cls, "__str__", Tprinter)So this works for triangles. How generic is it supposed to be? |