• Python 类的公有、私有成员


    我们先上结论┗( ▔, ▔ )┛

    结论

    __xx__:这种系统属性或方法,还没想好怎么测试,我们就看看用户自定义的吧
    | variate | from module import *| 类外 | 继承 |
    | ---- | ---- | ---- |----| ---- |
    | xx :公有变量 | ✔ | ✔ | ✔ |
    | _xx :单前置下划线 | ✘ | ✔ | ✔ |
    | __xx:双前置下划线 | ✘ | ✘ | ✘ |

    from module import * 测试部分
    a.py

    name = "name"
    _name = "_name"
    __name = "__name"
    

    test.py

    from a import *
    
    print(name)
    # print(_name)      #NameError: name '_name' is not defined
    # print(__name)      #NameError: name '__name' is not defined
    

    类外 测试部分

    class Person(object):
        name = "name"
        _name = "_name"
        __name = "__name"
    
        @staticmethod
        def method():
            print("method()")
    
        @staticmethod
        def _method():
            print("_method()")
    
        @staticmethod
        def __method():
            print("__method()")
    
    
    instance = Person
    print(instance.name)  # name
    print(instance._name)  # _name
    # print(instance.__name)         # AttributeError: type object 'Person' has no attribute '__name'
    instance.method()  # method()
    instance._method()  # _method()
    # instance.__method()     #AttributeError: type object 'Person' has no attribute '__method'
    
    

    继承 测试部分

    class PersonChild(Person):
        def out(self):
            print(instance.name)  # name
            print(instance._name)  # _name
            # print(instance.__name)        # AttributeError: 'PersonChild' object has no attribute '__name'
            self.method()  # method()
            self._method()  # _method()
            # self.__method()     # AttributeError: 'PersonChild' object has no attribute '__method'
    
    
    
    instance = PersonChild()
    instance.out()
    
  • 相关阅读:
    使用Eclipse调试Java程序的10个技巧
    向mysql中插入格式为"yyyyMMdd HH:mm:ss"的时间
    乐观锁和悲观锁
    js验证表单大全
    subclipse版本回滚功能
    (转)Linux(RedHat AS4)下架设subversion(svn)服务器
    Redhat5下安装Apache2与Subversion1.6.15
    (转)深入探讨 Java 类加载器
    (转)Java深度历险(一)——Java字节代码的操纵
    关于SVN 目录结构
  • 原文地址:https://www.cnblogs.com/adamr/p/13972017.html
Copyright © 2020-2023  润新知