访问可见性问题
- 在python中,希望变量不要随便调用,将变量私有化
1、私有变量,变量前加“__”
2、如果非要使用私有变量,可以用dir(class())去查看它真正的名字。
3、私有变量/函数,在类内部可以直接调用
4、如果想要体现一个变量/函数特别重要可以使用“_"
- 实例:
class Test:
def __init__(self,foo):
self.foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
test.__bar()
if __name__ =="__main__":
main()
- 以上可见:python没有从语法上严格保证私有属性或方法的私密性,它只是给私有属性或方法取了一个艺名来“妨碍”对它们的访问。
- 练习:写一个邮箱注册
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aa818fec217ce7c18957d5170027248a.png)
import random
class mailbox(object):
def __init__(self):
print("网易邮箱注册")
def name(self):
res = input("输入邮箱地址")
print("您输入的邮箱是:%s" % res)
self.password()
def password(self):
for i in range(4):
self.one = input("设置密码")
self.two = input("确认密码")
if self.one == self.two:
print("设置成功")
self.yanzhengma