1、使用注意

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比白河网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式白河网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖白河地区。费用合理售后完善,10余年实体公司更值得信赖。
单下划线的方法只是开发者之间的约定,解释器不做任何改变。
双下化下的方法,是私有方法,解释器会改名,改名策略和私有变量相同,【_类名__方法名】。方法变量都在类的【__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__': , '_Myclass__getname': , '_Myclass__getage': , '__dict__': , '__weakref__': , '__doc__': None}
print(a._Myclass__getname()) # tom
以上就是python私有方法的使用注意,希望对大家有所帮助。更多Python学习指路:创新互联Python教程