Apr-25-2020, 03:32 PM
(This post was last modified: Apr-25-2020, 03:32 PM by jamesbond112.)
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
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)