educative.io

Educative

How Can method of one class access the method of another class without creating/assigning object?

Dear Educative Community,

In the Class School , we have the following code,
getTotalPlayersInSchool(self):
length = 0
for n in self.teams:
length = length + (n.getNumberOfPlayers())
return length

But here getNumberOfPlayers() is from the class Team. Here how can the object ‘n’ from School access getNumberOfPlayers() without first doing something like this,
n = Team()
Please point out relevant previous lessons related to this, if this concept is mentioned there.

Thanks
Santhanakrishnan.


Type your question above this line.

Course: https://www.educative.io/collection/10370001/6201068373409792
Lesson: https://www.educative.io/collection/page/10370001/6201068373409792/5909785754992640

Hi @Santhankrishnan_Dhan

You got it mixed up, n is not an object of the School class, it is just an iterator used to iterate over teams. You can change it to any other variable and it would still work.

Hope this clears your confusion.

Thanks.

Thanks for replying, It is not about how iterator works.

Regardless of if it is “n” or something else, how can this iterator defined in one class can access a method from another class? Without instantiating to the class?.

Appreciate your help.

Thanks
Santhanakrishnan

Hi Santhankrishnan!
here n is accesing the getNumberOfPlayers() method because on line 49-50 we are adding the red_team and blue_team objects of team in school . So it can access all the methods of the team and calling on line 31.

I hope it will clear your confusion. If you still have any queries please let us know.
Thank you!