Python 类的公有、私有成员

时间:2020-11-14 00:40:51   收藏:0   阅读:36

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

结论

__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"

    def method(self):
        print("method()")

    def _method(self):
        print("_method()")

    def __method(self):
        print("__method()")


instance = Person()
print(instance.name)  # name
print(instance._name)  # _name
# print(instance.__name)         # AttributeError: ‘Person‘ object has no attribute ‘__nam
instance.method()  # method()
instance._method()  # _method()
# instance.__method()     # AttributeError: ‘Person‘ object has no attribute ‘__method‘

继承 测试部分

class PersonChild(Person):
    pass


instance = PersonChild()
print(instance.name)  # name
print(instance._name)  # _name
# print(instance.__name)        # AttributeError: ‘PersonChild‘ object has no attribute ‘__name‘
instance.method()  # method()
instance._method()  # _method()
# instance.__method()     # AttributeError: ‘PersonChild‘ object has no attribute ‘__method‘

原文:https://www.cnblogs.com/adamr/p/13972017.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!