当前位置:首页 > Python教程 > python技巧

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: Siteobject 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

 

原文:https://www.cnblogs.com/sea-stream/p/11431498.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐