'Setting conditions for a parameter in a class function
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?
Solution 1:[1]
type(arg) returns the type and not a string of the type.
Instead of type(radius) == 'int' you should use type(radius) == int
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | StrangeSorcerer |
