0

I read multiple article about OOP in python but I didn't find the answer. here is my sample code as a example :

class Point(object):
    """basic point"""
    def __init__(self, x, y):
        self.x = x
        self.y = y


class Circle(object):
    """basic circle object"""
    def __init__(self,center,radius):
        self.center = center  #should be a point object
        self.radius = radius

coord = Point(1, 2)
a = Circle(coord, 4)
b = Circle(4, 5)

If I understand correctly this is valid python code but the circle "b" doesn't have a Point object as the center. if there is a method in the circle object who use the center object to do a calculation (to calculate the circle's area for example) it will fail for the b object. Do I have to enforce type or is it the programmer responsibility to give a expected object type at the instantiation?

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
math
  • 11
  • 1
  • 1
    @jonrsharpe: I'm not sure that's the right duplicate. This question is more along the lines of "_do I have to_ implement type checking", but the dupe is along the lines of "_how do I_ implement type checking". – Bryan Oakley Feb 21 '16 at 16:08
  • Exactly, it is more about _do I have to_. I would think it's better to check type in the object definition so it will be easier to catch my error each time I instantiate it, but I'm not sure if it's the python way. – math Feb 21 '16 at 16:18

2 Answers2

1

As others have said, it is up to you to enforce typing.

However, Python widely uses the concept of duck typing, which means in your case, you don't necessarily need a Point object for the center, you just need something that behaves the same as your Point class. In this simple example, Point doesn't provide any methods; it's simply a class whose objects will have x and y attributes. That means your Circle could accept any object for its center as long as it provides x and y attributes, that is, provides the same interface as Point.

This means that the most important thing to do is document what interface your class provides, and what each function or method expects from its arguments.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

It is up to you to enforce types, and up to the caller to provide the proper data.

One of the underlying philosophies of the python community is that we're all responsible programmers. If it is critical that the type is enforced against accidental or malicious mistakes, you must build that into your objects.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685