Alejandro A
Alejandro A

Reputation: 1190

Can't call/ access internal class method Python

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

Upvotes: 0

Views: 375

Answers (1)

K. Prot
K. Prot

Reputation: 169

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

Upvotes: 1

Related Questions