Home > database >  Python - Calling function within class by using self vs class name
Python - Calling function within class by using self vs class name

Time:10-08

I have a sample code as following

class car:
     
    # init method or constructor
    def __init__(self, car_age, driver_age):
        self.car_age = car_age
        self.driver_age = driver_age
         
    def cal(self):
        
        return self.car_age   self.driver_age

    def classification(self):

        years = car.cal(self)

        if years > 15:
                ......

For the classification function, my questions:

  1. I tested with years = self.cal() and years = car.cal(self) , i.e. call the cal function by using self vs the car class, and found both ways would work and have the same result, but am wondering what are some potential differences of the two methods? Which one would you suggest to use?

  2. My colleague suggested me that I should not have self in the cal function, i.e. he suggested to write as years = self.cal(). But putting self in the cal function, i.e. years = car.cal(self) would still work. What are the differences in putting/not putting?

Thanks a lot everyone!

CodePudding user response:

Yes, both method do almost the samething under the hood, and are undisguinshable in simple code, like this.

Yet, doing self.cal() is the idiomatic way of doing this: we are signaling to the reader of our code that we are calling a method in the same instance. (A method is just the name given to functions bound to an object instance, or to a class).

The fact is that when calling a method in an instance, Python automatically insert the reference to that instance as the first parameter by creating an intermediate object when self.cal is processed - the resulting object is then called - when Python executes the parenthesis part of self.cal(...). All of this is completely transparent.

CodePudding user response:

years = self.cal() would call the method (cal()) of the existing class. That is, the class object car is using its own method to do that calculation.

I would say best practice would be to use self.cal() to avoid confusion with the existing instance and the object qua class.

  • Related