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?

Jenkins
  • 71
  • 4
  • 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 – Tomerikoo Apr 15 '21 at 15:29

2 Answers2

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
Navid Naseri
  • 123
  • 7
  • 7
    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()?](https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance) – Tomerikoo Apr 15 '21 at 15:18
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)
sahasrara62
  • 10,069
  • 3
  • 29
  • 44