python私有方法的使用注意
发布时间:2024-07-21 20:26:24

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:'Myclass'objecthasnoattribute'__getname'
#print(a.__getage())#AttributeError:'Myclass'objecthasnoattribute'__getage'
print(a.__dict__)#{'name':'tom','_age':18}
print(a.__class__.__dict__)#{'__module__':'__main__','__init__':<functionMyclass.__init_at0x01ABC4688>,'_Myclass__getname':<functionMyclass._getnameat0x01B061500>,'_Myclass__getage':<functionMyclass.__getageat0x01B064B>,'__dict__':<attribute'__dict__'of'Myclass'objects>,'__weakref__':<attribute'__weakref__'of'Myclass'objects>,'__doc__':None}
print(a._Myclass__getname())#tom以上是使用python私人方法的注意事项,希望对大家有所帮助。更多Python学习指导:python基础教程
下一篇 python保护变量是什么
