-2

I am just learning how to make classes and I was trying to complete one of my assignments but I was having difficulty making one the variables private. I am making an Account class that stores the ID, balance, and annual interest rate. All of these have default values or can be set. My code looks like this

class Account:
def __init__(self, ID=0, balance=100, annualInterestRate=0.0):
    self.ID = int(ID)
    self.balance = float(balance)
    self.annualInterestRate = float(annualInterestRate)
account = Account()
print(account.ID)
print(account.balance)
print(account.annualInterestRate)   

Everything works fine, but if I try making the the variables private(by adding "__" before the variable), and then try accessing the values, I get an AttributeError. Anyone know what I am doing wrong?

    ... 
    self.__ID = int(ID)
    self.__balance = float(balance)
    self.__annualInterestRate = float(annualInterestRate)
account = Account()
print(account.ID)
print(account.balance)
print(account.annualInterestRate)   
Muhammad Khan
  • 25
  • 2
  • 6
  • Its due to [name mangling](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references). – Marcin Nov 24 '14 at 09:23
  • 4
    Short version: simply use a single underscore. Or, for what it's worth: don't bother with private variables (perhaps only when you use properties): your first version is fine. Since Python doesn't enforce non-access of private variables, I never see a use for it. –  Nov 24 '14 at 09:34
  • 2
    You changed their name, why do you expect the old name to keep working? Also, isn't the fact that that doesn't work anymore exactly what you're trying to do when making things private? – RemcoGerlich Nov 24 '14 at 09:35
  • RemcoGerlich is right. In general OOP terms, a 'private' field cannot be accessed outside the declaration scope (in this case outside the class definition) – fr1tz Nov 24 '14 at 09:42
  • You should talk to your class mate. It seems you are both in the same class and asking the same question: http://stackoverflow.com/questions/27117010/private-instance-variables-in-python-3 – Andy Nov 25 '14 at 02:48

1 Answers1

1
>>> class Foo:
...     def __init__(self, value):
...         self.__value = value
...
>>> foo = Foo(42)
>>> print(foo.value)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'value'

You changed their name, why do you expect the old name to keep working? – RemcoGerlich

I think you meant:

>>> print(foo.__value)

But it doesn't work as well:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__value'

Finally:

>>> print(foo._Foo__value)
42

Its due to name mangling. – Marcin

GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52