Home > database >  'Tuple' object is not callable in classes
'Tuple' object is not callable in classes

Time:03-29

I'm learning classes right now and every time that I try to run this code I get " 'tuple' object is not callable'". I know that I can't access elements from a tuple using only parentheses I. Can someone tell what is wrong with my code?

class Line:
    
    def __init__(self, coor1, coor2):
        self.coor1 = coor1
        self.coor2 = coor2

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

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

li.distance()

CodePudding user response:

You are accessing coor1 and coor2 which both are tuples using round brackets, so Python tries to call them as a function and fails.

Remove the round brackets:

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

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

CodePudding user response:

The parentheses around the indexing operations lead Python to attempt to interpret the tuples as functions. Remember that parentheses can change the semantic meaning of your code.

To resolve, remove the parentheses around the indexing operations:

class Line:
    
    def __init__(self, coor1, coor2):
        self.coor1 = coor1
        self.coor2 = coor2

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

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

# Prints 9.433981132056603
print(li.distance()) 

CodePudding user response:

When you access the items from your tuple, you don't want the parenthesis around your square brackets. Just the square brackets will source the value from your tuple. Like this shortened example.

class Line:
    
    def __init__(self, coor1, coor2):
        self.coor1 = coor1
        self.coor2 = coor2

    def distance(self):
       print(self.coor2[0]-self.coor1[0])

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

li.distance() 
  • Related