首页 > 编程笔记 > Python笔记

Python类的访问权限(public、 private、protected)

与 C++、C#、Java 等语言相似,Python 支持将类的属性和方法设置成特定的访问权限,但不是通过关键字区分,而是使用一套约定式的规则:
以下例子展示了三种不同访问权限的属性和方法:
class Class1:
    public1= 111
    _protected1 = 222
    _private1 = 333
    def publicFunc1(self):
        pass
    def _protectedFunc1(self):
        pass
    def __privateFunc1(self):
        pass

class Class2(Class1):
    public2 = 444
    _protected2 = 555
    __private2 = 666
    def publicFunc2(self):
        pass
    def _protectedFunc2(self):
        pass
    def __privateFunc2(self):
        pass

c1 = Class1()
    print(c1.public1)
    print(c1._protected1)
    print(c1.__private1)
c1.publicFunc1()
c1._protectedFunc1()
c1.__privateFunc1()

c2 = Class2()
    print(c2.public1)
    print(c2._protected1)
    print(c2.__private1)
    print (c2.public2)
    print(c2._protected2)
    print(c2.__private2)
c2.publicFunc1()
c2._protectedFunc1()
c2.__privateFunc1()
c2.publicFunc2()
c2._protectedFunc2()
c2.__privateFunc2()
上述代码的运行结果如下所示:

>>> class Class1:
...          public1= 111
...          protected1 = 222
...          _private1 = 333
...          def publicFunc1(self):
...              pass
...          def _protectedFunc1(self):
...              pass
...          def __privateFunc1(self):
...              pass

>>> class Class2(Class1):
...          public2 = 444
...          _protected2 = 555
...          __private2 = 666
...          def publicFunc2(self):
...              pass
...          def _protectedFunc2(self):
...              pass
...          def __privateFunc2(self):
...              pass

>>> c1 = Class1()
>>> print(c1.public1)
111
>>> print(c1._protected1)
222
>>> print(c1.__private1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    print(c1.__private1)
AttributeError: 'Class1' object has no attribute '__private1'
>>> c2 = Class2()
>>> print(c2.public1)
111
>>> print(c2._protected1)
222
>>> print(c2.__private1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    print(c2.__private1)
AttributeError: 'Class2' object has no attribute '__private1'
>>> print (c2.public2)
444
>>> print(c2._protected2)
555
>>> print(c2.__private2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    print(c2.__private2)
AttributeError: 'Class2' object has no attribute '__private2'
>>> c2.publicFunc1()
>>> c2._protectedFunc1()
>>> c2.__privateFunc1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    c2.__privateFunc1()
AttributeError: 'Class2' object has no attribute '__privateFunc1'
>>> c2.publicFunc2()
>>> c2._protectedFunc2()
>>> c2.__privateFunc2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    c2.__privateFunc2()
AttributeError: 'Class2' object has no attribute '__privateFunc2'

可以看到,在外部直接访问类的私有属性或方法时触发了 AttributeError 异常。

所有教程

优秀文章