在Python中生成私有变量

2024-06-02 06:05:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在学习如何上课,我试图完成我的一个作业,但我有困难,使一个变数私人化。我正在制作一个Account类,它存储ID、余额和年利率。所有这些都有默认值或可以设置。我的代码是这样的

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)   

一切正常,但是如果我尝试将变量设为私有(在变量前面加上“uuu”),然后尝试访问这些值,就会得到AttributeError。有人知道我做错了什么吗?在

^{pr2}$

Tags: 代码selfid作业accountfloatclass余额
1条回答
网友
1楼 · 发布于 2024-06-02 06:05:51
>>> 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

我想你是说:

^{pr2}$

但它并不起作用:

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

最后:

>>> print(foo._Foo__value)
42

Its due to name mangling. – Marcin

相关问题 更多 >