第十七集:三大特性-封装

'''
对成员和方法进行封装受保护
不能全部封装 被封装的成员主要供类的内部使用
封装的属性供内部使用
共有的public 受保护的 protected 私有的private
类的外部 可以 不可以 不可以
类的内部 可以 不可以(python可以) 不可以
成员私有化,其实就是改了成员的名字
私有化 :_类型__属性 获取成员的属性
'''


class Person():
name = '小怪'

_age = 22 # 在成员前面加一个_代表受保护的

__sex = '女' #在成员前面加两个__代表是私有的

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

def _sing(self):
print(f'{self.name}会唱歌')

def fuc(self):
self.__play()

def play(self):
print('我会打扮')

def __play(self):
print('我会打扮')


# 实例化对象
zxy = Person('晓艳', 24, '女')
print(zxy._Person__sex) #_类名__属性 访问私有属性
print(zxy)
# 查看对象成员
zxy.member = zxy.__dict__
print(zxy.__dict__) # 查看对象所有属性
# print(zxy.__dict__, type(zxy.__dict__)) # 查看当前对象的所有属性
print(zxy.member['name'])
# zxy.sing()
print(zxy.__dir__()) # 获取当前类的所有成员信息
ss = zxy.__getattribute__('member')
print(ss)

print('我的名字:',zxy.name)
# print('我的年龄:',zxy.age) #如果不指定是哪个 age 和_age不是一个属性
print('我的年龄:',zxy._age)
# print('我的性别:',zxy.__sex)
# 结果
# Traceback (most recent call last):
# File "D:/Autotest/cyz/day7Object/面向对象-三大特性-封装.py", line 45, in <module>
# print('我的性别:',zxy.__sex)
# AttributeError: 'Person' object has no attribute '__sex'
# <__main__.Person object at 0x000002B336314A00>
# {'name': '晓艳', '_age': 24, '_Person__sex': '女', 'member': {...}}
# 晓艳
# 晓艳会唱歌
# ['name', '_age', '_Person__sex', 'member', '__module__', '__init__', 'sing', 'play', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
# {'name': '晓艳', '_age': 24, '_Person__sex': '女', 'member': {...}}
# 我的名字: 晓艳
# 我的年龄: 24

zxy._sing() #
zxy.fuc() #
posted @ 2022-03-02 22:46  冬天里的狐狸  阅读(29)  评论(0编辑  收藏  举报