Home > Back-end >  Setting conditions for a parameter in a class function
Setting conditions for a parameter in a class function

Time:03-22

I am trying to set a condition that only allows an integer value that is greater than 0 to be used when initialising a new class instance. Anything else would return an error.

class Circle:
    def __init__(self, radius):
        if type(radius) == 'int' and radius > 0:
            self.radius = radius 
        else:
            print("Incorrect value for radius")

circle1 = Circle(2) #output: Incorrect value for radius
circle2 = Circle(-3) #output: Incorrect value for radius
circle3 = Circle('a') #output: Incorrect value for radius

Circle 1 should be correct but fails the case, is there something that I am doing incorrect to allow for integer values and integer values greater than 0 to be used for the radius when creating a new circle class?

CodePudding user response:

type(arg) returns the type and not a string of the type.

Instead of type(radius) == 'int' you should use type(radius) == int

  • Related