0

i´m having an attribute error on my code when i try to encapsulate a variable and i cant see why.

class Car():

    def __init__(self):

       self.__doors=4
       self.sizeChasis=250
       self.colorChasis=120
       self.running=False

    def start(self,letsgo):
        self.running=letsgo

        if(self.running):
            return "Car is on"
        else:
            return "Car is off"

    def state(self):
        print("The car has ", self.__doors, "doors. And ", self.sizeChasis, "and ", self.colorChasis)

myCar=Car()

print("A: ",myCar.sizeChasis)
print("B: ", myCar.__doors, "doors")

print(myCar.start(True))
myCar.state()

And here is the error:

rint("B: ", myCar.__doors, "doors")
AttributeError: 'Car' object has no attribute '__doors'

Probably is an easy question but i cant see the solution.

Thanks

SEVENELEVEN
  • 187
  • 1
  • 11

1 Answers1

0

When you have two underscores in front of a variable in a class, it is a "private variable", meaning you can't use it outside of the class. To fix this, remove the two underscores:

class Car():

    def __init__(self):

       self.doors=4
       self.sizeChasis=250
       self.colorChasis=120
       self.running=False

    def start(self,letsgo):
        self.running=letsgo

        if(self.running):
            return "Car is on"
        else:
            return "Car is off"

    def state(self):
        print("The car has ", self.doors, "doors. And ", self.sizeChasis, "and ", self.colorChasis)

myCar=Car()

print("A: ",myCar.sizeChasis)
print("B: ", myCar.doors, "doors")

print(myCar.start(True))
myCar.state()
Ayush Garg
  • 2,234
  • 2
  • 12
  • 28