Search code examples
pythonclassmagic-methods

Class __str__ magic-methods


Hi I am learning classes and special methods and I having trouble with the code below, as I cant seem to figure out how to get the def __ str__ to work, it prints none

class Circle:
    def __init__(self,radius):
        self.radius = radius
        print(f'Circle of radius {radius}')
    def circumference (self):
        self.circumference=round(2*3.14*self.radius,2)
    def __str__(self):
        return f"the circumference is: {self.circumference}"

circle_1=Circle(5)
print(circle_1.circumference())

Solution

  • class Circle:
        def __init__(self,radius):
            self.radius = radius
            print(f'Circle of radius {radius}')
        
        def circumference (self):
            return round(2*3.14*self.radius,2)
        
        def __str__(self):
            return "the circumference is: {}".format(self.circumference())
         
    circle_1=Circle(5) 
    print(circle_1)
    

    You should try this.