Search code examples
pythonclassobjectdynamic-typing

Why we don't have to define the type of an argument when creating an object from a class in Python?


I am new to Python and I have just created a class as part of the online course I am taking.

from math import sqrt

class Line:

def __init__(self,coor1,coor2):
    self.coor1=coor1  #tuple (x1,y1)
    self.coor2=coor2  #tuple (x2,y2)

def distance(self):
    return sqrt((self.coor2[0]-self.coor1[0])**2+(self.coor2[1]-self.coor1[1])**2)

def slope(self):
    return (self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0])

This is a class for Line and helps me find the distance between two coordinates. I am wondering, since a coordinate needs to be a tuple, how does Python know this? Why don't I need to define this in the def __init__?


Solution

  • It's not python who knows that's a tuple! you should handle it if you want python to presume that coor1 and coor2 are tuples. now if you create an object of your class like :

    line1 = Line("hi","Sorath")
    

    coor1 would be equal to hi and coor2 would be equal to Sorath and both of them are strings.

    coor1 and coor2 can be everything, you should define the type of them while you are passing values or when you are writing __init__ !

    def __init__(self,coor1,coor2):
        if type(coor1)==tuple:
            self.coor1=coor1  #tuple (x1,y1)
        else:
            self.coor1 = () #empty tuple
    
        if type(coor2)==tuple:
            self.coor2=coor2  #tuple (x2,y2)
        else:
            self.coor2 = () #empty tuple