0

Have a class with some methods, in one if this method I call another method which returns an error.

Code sample:

class Car:

    def __init__(self,Km,Brand):
        self.car_name=Brand
        self.car_kms=Km

    @classmethod
    def get_kms_updated(self):
        new_kms=__get_kms_cheating(self.car_kms,10)
        self.car_kms=new_kms
    
    @classmethod
    def __get_kms_cheating(self,int_km):
        return self.kms+int_km

Error message

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)
<ipython-input-29-1cdd478d0a60> in <module>
----> 1 first_car.get_kms_updated()

<ipython-input-27-904633893463> in get_kms_updated(self)
      7     @classmethod
      8     def get_kms_updated(self):
----> 9         new_kms=__get_kms_cheating(self.km,10)
     10         self.car_kms=new_kms
     11 

NameError: name '_Car__get_kms_cheating' is not defined
Alejandro A
  • 1,150
  • 1
  • 9
  • 28
  • 1
    Please fix your indentation. It's not clear what functions (if any) are supposed to be members of the `Car` class. – John Gordon Jul 21 '20 at 16:45
  • btw It is traditional when you have a `@classmethod` for the method to be like: `def get_kms_updated(cls):` – quamrana Jul 21 '20 at 16:50
  • 1
    The entire point of class methods is that they don't need access to `self`. But those functions are definitely using `self`, so why do you want them to be class methods? – John Gordon Jul 21 '20 at 17:02

1 Answers1

1

First of all, there are several errors in your program.

  1. You should define class members, if you want to use in class methods. Like Car.car_kms = Km, otherwise you will receive an error - type object 'Car' has no attribute 'car_kms'
  2. You should call the class method like this - Car.__get_kms_cheating()
  3. We recommend that the parameters of the class method be written as cls instead of self which is for instance method.

I think this is what you want

class Car:
    def __init__(self, Km, Brand):
        self.car_name = Brand
        Car.car_kms = Km
        
    @classmethod
    def get_kms_updated(cls):
        new_kms = Car.__get_kms_cheating(10)
        Car.car_kms = new_kms
        
    @classmethod
    def __get_kms_cheating(cls, int_km):
        return cls.car_kms + int_km
K. Prot
  • 169
  • 4
  • Thank you very much, I need to learn a lot and your explanation really helped – Alejandro A Jul 21 '20 at 17:37
  • @AlejandroA No problem, looking at this answer here.https://stackoverflow.com/questions/17134653/difference-between-class-and-instance-methods may also help you. Btw, I don't know what the usage scenario of this program is, I personally feel that there is no need to use class methods here. – K. Prot Jul 21 '20 at 18:11