1

Consider the following code:

class Time:

    def __init__(self,hours,minutes):

        self.minutes = minutes
        self.hours = hours

    def addTime(t1):

        time = t1.minutes + t1.hours
        return time

I don't understand the logic behind why I can call t1.minutes and t1.hours in the method addTime. Why the parameter t1 can be used with the instances self.minutes,self.hours of the class Time ?

moth
  • 1,833
  • 12
  • 29
  • 4
    `t1` is `self`. In a class the first attribute passed to all methods is the class instance its self. Its just that you have chosen in your addTime method to label the class instance as `t1` instaed of `self` this is perfectly valid. Convention says you should call it `self` but thats just a nameing convention. your not obliged to call it that, you can call it anything you like. and in your case you have called it `t1` but thats just the name you have given to access the class instance in addTime method – Chris Doyle Mar 02 '20 at 11:20
  • 1
    Read up on [Python Classes and Objects, Section "The self|Class and Instance Variables"](https://www.geeksforgeeks.org/python-classes-and-objects/) – stovfl Mar 02 '20 at 11:22
  • Related: [Naming the self parameter something else](https://stackoverflow.com/q/37885330/7851470) – Georgy Mar 02 '20 at 11:29
  • Does this answer your question? [What is the purpose of the word 'self', in Python?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python) – Chris Doyle Mar 02 '20 at 11:39

1 Answers1

2

The first parameter passed to a class method is the class instance. So if you have a class method that takes an int and increase its count by that int. when you call the class method you will pass 1 parameter but in your class method you will have defined 2 parameters, the first being the name you want to use to refer to the class instance and the second being the actual parameter being passed from the calling code.

class MyClass:
    def __init__(self):
        self.counter = 0

    def increase(mc1, increase_by):
        mc1.counter += increase_by

mines = MyClass()
print(mines.counter)
mines.increase(50)
print(mines.counter)

So when my code calls increase and passed an int. python will actually pass two parameters, the class instance and the integer. when you receive these i receive these in my method i am labeling the class instance object i received as mc1 and the int as increase_by

so using mc1 name i can access all the class instance attributes as mc1 is pointing to the class instance

Chris Doyle
  • 10,703
  • 2
  • 23
  • 42