0

Consider the class below.

class Car:
    def __init__(self, speed):
        self.speed = speed
    def accelerate(self):
        self.speed += 5

Suppose you instantiate a new object of the class, i.e., ferrari = Car(50), is there a way to prevent ferrari.speed from being accessed from outside of the class?

Thanks for any help,

Jack

  • Python does not have strong enforcement of "private" variables. By convention, variables that should not be accessed are pre-pended with an underscore, i.e. `self._speed = speed`. This is "privacy by convention" – juanpa.arrivillaga Jan 23 '18 at 17:42
  • Thanks @juanpa.arrivillaga. What if you don't want the user of a package you're making to have access to certain attributes of a class? Do you just have to refactor your code? –  Jan 23 '18 at 17:43
  • Sorry, again, *there are no private variables* in Python. If you want to signal to users of a package that a variable is not meant to be accessed, you pre-pend with an `_`. So yea, I guess you would refractor your code. I'm not exactly sure what you are getting at, though. – juanpa.arrivillaga Jan 23 '18 at 17:46

0 Answers0