私有属性和方法

私有属性和方法

在Java和C++中,私有化属性和方法用的是private和protected关键字,来控制属性和方法是否能被外界或者子类访问调用,在Python中用两条下划线就可以定义私有属性和方法,注意不要将魔法方法与自定义的私有属性和方法搞混,都是两条下划线开头,但是两者是有很大区别的。

代码

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Course:
...     __private_name = "Python"
...     def __get_private_name(self):
...         return self.__private_name
...
>>> c = Course()
>>> c.__private_name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__private_name'
>>> c.__get_private_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__get_private_name'. Did you mean: '_Course__private_name'?
>>>

可以看到无法用对象直接进行访问调用

posted on 2025-06-24 01:34  burgess0x  阅读(26)  评论(0)    收藏  举报