使用python私有方法的注意事项

393次阅读
没有评论

使用python私有方法的注意事项

使用python私有方法注意

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

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

使用python私有方法实例

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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-03-27发表,共计989字。
新手QQ群:570568346,欢迎进群讨论 Python51学习