• 技术文章 >Python技术 >Python基础教程

    python私有方法的使用注意

    小妮浅浅小妮浅浅2021-05-08 15:57:53原创1616

    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私有方法
    品易云
    上一篇:python保护变量是什么 下一篇:python析构函数如何使用

    相关文章推荐

    • python哈希散列的映射• python中树有哪些种类• python装饰器如何保留原函数信息• python装饰器有哪些作用• python动态存取属性如何实现• python zip函数的使用注意• python zip_longest如何使用• python dict.item()方法遍历字典• python序列操作的整理• python字符串中有哪些方法• python格式字符串是什么• python字符串方法format()如何使用• python列表的创建和存放• python列表添加和删除的方法• python默认索引是什么• python列表操作符有哪些• python列表中sort()参数的使用• python如何创建GUI程序

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网