Skip to main content
 首页 » 编程设计

python之在 Python 中声明私有(private)变量

2025年05月04日15jiqing9006

<分区>

我正在用 Python 编写一个银行应用程序,并从这里阅读一些源代码 Banking Application . balance 类定义如下:

class Balance(object): 
    """ the balance class includes the balance operations """ 
 
    def __init__(self): 
        """ instantiate the class """ 
        self.total = 0 
 
    def add(self, value): 
        """ add value to the total 
        Args: 
            value (int): numeric value 
        """ 
        value = int(value) 
        self.total += value 
 
    def subtract(self, value): 
        """ subtract value from the total 
        Args: 
            value (int): numeric value 
        """ 
        value = int(value) 
        self.total -= value 

我的问题

由于不应在类之外访问余额详细信息,因此我们应该将属性 self.total 定义为 self.__total 因为我们应该将其设为 private 而不是 public 变量?我的思路在这里正确吗?