- Python 对于类的成员没有严格的访问控制限制,这与其他面向对象语言有区别。关于私有属性和私有方法,有如下要点:
1、通常我们约定,两个下划线开头的属性是私有的(private)。其他为公共的(public)。
2、类内部可以访问私有属性(方法)
3、类外部不能直接访问私有属性(方法)
4、类外部可以通过“_类名__私有属性(方法)名”访问私有属性(方法)
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 09:01:26 2021
@author: daicong
"""
class Soulution():
__identify = "演员"#私有属性,通过dir可以查到_TV.__identify
def __init__(self,name,age):
self.name = name
self.__age = age #将实例属性私有化
def introduce(self):
print("她的年龄是{0}".format(self.__age))#直接访问私有化的实例
print(self.name,"的职业是:",Soulution.__identify)#类内部可以直接访问私有属性
self.__wife()
def __wife(self):#私有实例方法 通过 dir 可以查到_Soulution__wife
print("宋轶真的好美")
res = Soulution('宋轶',31)#实例化Soulution
"""打印共有属性name"""
print(res.name)
"""打印所有私有属性"""
print(dir(res))
"""打印私有属性wife"""
print(dir(res._Soulution__wife))
"""调用类的introduce方法"""
res.introduce()
"""打印私有属性age"""
print(res._Soulution__age)
#print(res.__age)#会报错,因为直接访问私有属性
#res.__wife()#会报错,因为直接访问私有方法
运行结果为
宋轶
['_Soulution__age', '_Soulution__identify', '_Soulution__wife', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'introduce', 'name']
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
她的年龄是31
宋轶 的职业是: 演员
宋轶真的好美
31