Accessing inner functions in a class

Hi there!

I am a beginner in python so I like to experiment. I was trying object oriented programming when I got stuck on this problem.
Here is my code.

The problem is in the last line of code. How can I access a nested inner function using object of a class?

It is for general practise only.

class Train:
    def __init__(self,name,fare,seats):
        self.name=name
        self.fare=fare
        self.seats=seats

    def getStatus(self):
        print(f"The name of the train is {self.name}")
        print(f"The number of seats in the train is {self.seats}")

    def fareInfo(self):
        print(f"The fare of the train is {self.fare}")

    def bookTicket(self):
        if(self.seats>0):
            print("your ticket has been booked! Your seat number is {self.seat}")
            self.seats=self.seats-1
        else:
            print("Sorry! This train is full!")

    def seatslist(self):
        seatno=[]
        for i in range(1,self.seats+1):
         seatno.Train.append(i)
         print(seatno,end="")
         def cancelticket(self,n):
             for n in seatno:
                seatno.remove(n)
             print(f"The following ticket numbers are available:{seatno} ")
    


Intercity= Train("Intercity :14015",90,10)
Intercity.getStatus()
Intercity.fareInfo()
Intercity.seatslist()
Intercity. cancelticket(7)        #here I want to use the  nested function
                                                                                 
                                                                        

I don’t think you can or should even try this…
If you want to add more behavior to this, you’d either add arguments to the function call OR implement it as another object.

The only feasable way to call a function within a function would be if the outer function returns the inner function → because a function is treated as it’s return value. Hence nested calls are not possible.

1 Like

@Jagaya…Thanks so much. I never thought of these ideas and your answers are really helping me a lot to learn Python. Sometimes I get stuck at a problem and can spend whole day on that problem which I think is very ineffective. I hope to overcome this bad habit soon.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.