首页IT科技python私有方法的使用注意

python私有方法的使用注意

时间2025-04-30 17:16:14分类IT科技浏览3572
导读:1、使用注意...

1          、使用注意

单下划线的方法只是开发者之间的约定          ,解释器不做任何改变          。

双下化下的方法               ,是私有方法     ,解释器会改名          ,改名策略和私有变量相同               ,【_类名__方法名】               。方法变量都在类的【__dict__】中可以找到     。

2               、实例

classMyclass: def__init__(self,name,age=18): self.name=name self._age=age def__getname(self): returnself.name def__getage(self): returnself.name a=Myclass("tom") #print(a.__getname())#AttributeError:Myclassobjecthasnoattribute__getname #print(a.__getage())#AttributeError:Myclassobjecthasnoattribute__getage print(a.__dict__)#{name:tom,_age:18} print(a.__class__.__dict__)#{__module__:__main__,__init__:<functionMyclass.__init__at0x01ABC468>,_Myclass__getname:<functionMyclass.__getnameat0x01B06150>,_Myclass__getage:<functionMyclass.__getageat0x01B064B0>,__dict__:<attribute__dict__ofMyclassobjects>,__weakref__:<attribute__weakref__ofMyclassobjects>,__doc__:None} print(a._Myclass__getname())#tom

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
石竹怎么养家庭养法(石竹的养殖方法图片) 新网域名注册服务网站(新网域名变更流程图解)