python私有方法的使用注意
2023-03-20 15:32:39 时间
1、使用注意
单下划线的方法只是开发者之间的约定,解释器不做任何改变。
双下化下的方法,是私有方法,解释器会改名,改名策略和私有变量相同,【_类名__方法名】。方法变量都在类的【__dict__】中可以找到。
2、实例
class Myclass: def __init__(self,name,age=18): self.name = name self._age = age def __getname(self): return self.name def __getage(self): return self.name a = Myclass("tom") #print(a.__getname()) # AttributeError: 'Myclass' object has no attribute '__getname' #print(a.__getage()) # AttributeError: 'Myclass' object has no attribute '__getage' print(a.__dict__) # {'name': 'tom', '_age': 18} print(a.__class__.__dict__) # {'__module__': '__main__', '__init__': <function Myclass.__init__ at 0x01ABC468>, '_Myclass__getname': <function Myclass.__getname at 0x01B06150>, '_Myclass__getage': <function Myclass.__getage at 0x01B064B0>, '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__weakref__': <attribute '__weakref__' of 'Myclass' objects>, '__doc__': None} print(a._Myclass__getname()) # tom
以上就是python私有方法的使用注意,希望对大家有所帮助。更多Python学习指路:python基础教程
相关文章
- 一个python程序员对计算机的分类和发展史的介绍
- 在IT开发中工作种类的分类
- Python学习方法和如何养成python高手
- 程序员用到的5种常见的Python解释器
- Python2和Python3的区别和代码转换
- Python的优势和缺点、应用领域介绍
- 如何选择编程语言以及编程语言的分类
- spring逻辑事务和物理事务区别
- Windows系统 - 安装Python教程(详细步骤)
- 在Mac OS系统中安装Python教程
- python变量命名规范方法有哪些
- Python代码格式书写规范
- python基础数据类型分类
- 使用 Promise 时的5个常见错误,你占了几个!
- 重新审视前端模块的调用, 执行和加载之间的关系
- Python调用WPS进行文档转换PDF及PDF转图片
- Python网络请求-aiohttp
- Python网络请求-httpx
- Python语法-多进程、多线程、协程(异步IO)
- Python网络请求-requests、JSON转换