Python Forum
Dynamically implement __str__ if not implemented
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamically implement __str__ if not implemented
#1
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)
Reply
#2
for the type of function you are describing, you should use __repr__
Reply
#3
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?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020