python的访问性问题

白昼怎懂夜的黑 提交于 2020-03-03 04:07:39

python和C++、Java等语言不同,其对象属性和方法的访问权限只有两种:private(私有)、public(公有)。

1. 公有和私有

一般情况下,python类中的属性为公有,若想使其变为私有,则在给属性和方法命名时,用两个下划线开头:

class Test:
    """docstring for Test"""

    def __init__(self, content):
        self.__content = content

    def __say(self):
        print('say something:')
        print(self.__content)


def main():
    test = Test('hello')
    # AttributeError: 'Test' object has no attribute '__content'
    print(test.__content)
    # AttributeError: 'Test' object has no attribute '__say'
    test.__say()


if __name__ == '__main__':
    main()

注:

  • 实际开发中,并不建议将属性或方法设置为私有(会导致子类无法访问该属性或方法);
  • 通常让属性或方法名以单下划线开头表示该属性或方法为protected(保护的),但这中做法只具有识别意义,并非其他语言中的protected,外界仍然可以访问这样的属性和方法。

2. @property
将对象的属性设置为protected的时(字面意义),需要通过getter和setter函数来访问,python中提供的机制是@property:

class Person(object):
    """docstring for Person"""

    def __init__(self, name, age):
        self._name = name
        self._age = age

    # getter函数
    @property
    def name(self):
        return self._name
    
    # getter函数
    @property
    def age(self):
        return self._age

    # setter函数
    @age.setter
    def age(self, age):
        self._age = age


def main():
    person = Person('Helen', 18)
    # 这里访问的其实是函数age()
    print(person.age)
    # 这里实际上调用了age的setter函数
    person.age = 20
    print(person.age)
    # 由于没有给_name设置setter函数,这里会报错:can't set attribute
    person.name = 'Zoey'

if __name__ == '__main__':
    main()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!