math
math

Reputation: 11

Expected behavior of class definition in python

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?

Upvotes: 0

Views: 105

Answers (2)

chepner
chepner

Reputation: 532093

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.

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 386325

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.

Upvotes: 0

Related Questions