社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

为什么在下面的Python代码中可以打印私有成员_分子和_分母?[重复]

Dexter • 3 年前 • 1014 次点击  

我来自Java世界,正在阅读Bruce Eckels的书 Python 3模式、配方和习惯用法 .

在阅读有关类的内容时,它接着说,在Python中,不需要声明实例变量。你只要在构造器中使用它们,它们就在那里。

例如:

class Simple:
    def __init__(self, s):
        print("inside the simple constructor")
        self.s = s

    def show(self):
        print(self.s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

如果这是真的,那么任何类的对象 Simple 可以改变变量的值 s 课外活动。

例如:

if __name__ == "__main__":
    x = Simple("constructor argument")
    x.s = "test15" # this changes the value
    x.show()
    x.showMsg("A message")

在Java中,我们学习了公共/私有/受保护变量。这些关键字是有意义的,因为有时你需要一个类中的变量,而这个类之外的任何人都无权访问它。

为什么Python中不需要这样做?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132167
 
1014 次点击  
文章 [ 1 ]  |  最新文章 3 年前