2

I am trying to do the following exercise from a python textbook:

Write a definition for a class named Circle with attributes center and radius, where center is a Point object and radius is a number.

I have written the following code:

class Point: def __init__(self , x , y): self.x = x self.y = y class Circle: def __init__(self , center , radius): self.center = center self.radius = radius c = Point(0 , 0) r = 75 c1 = Circle(c , r) c2 = Circle((1 , 0) , 2) 

This seems to work. But the thing is I have created the second Circle object c2 by specifying a tuple (1 , 0) as the center which is not a Point object.

How do I make sure that the Circle class takes only Point object as the center argument?

1
  • 1
    The point is, that if you do pass a tuple, the code will probably fail at some point. You will probably have somewhere circle.center.x. If you passed a tuple as the center, that will raise an AttributeError as tuples don't have an x attribute Commented Apr 15, 2021 at 15:29

2 Answers 2

2

Check input types with built-in type() function

class Circle: def __init__(self , center , radius): if type(center) != Point: raise Exception('Input type is not Point Class') self.center = center self.radius = radius 
Sign up to request clarification or add additional context in comments.

1 Comment

Since we're dealing with classes, and inheritance is a valid option, it is better to use if not isinstance(center, Point) than type. See What are the differences between type() and isinstance()?
1

you can use dataclasses here

from dataclasses import dataclass @dataclass class Point: x: int y: int @dataclass class Circle: center: Point radius:int def __post_init__(self): if not isinstance(self.center, Point): raise Exception("center is not a instance of Point class") c = Point(0 , 0) r = 75 # using with Point object, No error c1 = Circle(c , r) # no error # using with simple tuple object # Exception: center is not a instance of Point class will come c2 = Circle((1 , 0) , 2) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.