python 私有方法

test.py

#!/usr/bin/python3
class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private
    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)
    def __foo(self):          # 私有方法
        print('a')
    def foo(self):            # 公共方法
        print('b')
        self.__foo()
x = Site('xiaoming', 'www.runoob.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

输出

bogon:testdir macname$ python3 test.py 
name  :  xiaoming
url :  www.runoob.com
b
a
Traceback (most recent call last):
  File "test.py", line 22, in <module>
    x.__foo()      # 报错
AttributeError: 'Site' object has no attribute '__foo'

参考/:

https://www.runoob.com/python/python-files-io.html
https://www.cnblogs.com/bigberg/p/6430095.html
https://www.runoob.com/python3/python3-class.html

猜你喜欢

转载自www.cnblogs.com/sea-stream/p/11431498.html