Misu
Misu

Reputation: 69

Dynamically implement __str__ if not implemented

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)

Upvotes: 0

Views: 534

Answers (1)

jsbueno
jsbueno

Reputation: 110456

You should just use a classbody, and a regular superclass with a default __str__ - it is at the sametime the normal thing to do, and does what you want.

That said, your strFix function plugs an __str__ method on the instance, and that won't work - you have to set __str__ on the class itself.

And also, no need to use setattr when = suffices:

def strFix(instance):
    cls = instance.__class__
    if "__str__" not in cls.__dict__:
        cls.__str__ = Tprinter

Upvotes: 1

Related Questions