-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)   
5
  • Its due to name mangling. Commented Nov 24, 2014 at 9: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. Commented Nov 24, 2014 at 9: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? Commented Nov 24, 2014 at 9: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) Commented Nov 24, 2014 at 9:42
  • You should talk to your class mate. It seems you are both in the same class and asking the same question: stackoverflow.com/questions/27117010/… Commented Nov 25, 2014 at 2:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.