封装
- 封装
- 封装的级别
- 获取对象的所有成员
code:_5packaging.py
# ***************************************************************
"""
封装:使用特殊的语法对成员属性和成员方法进行包装,达到保护和隐藏的目的
但是封装是为了限制部分访问和控制,而不是全部限制(不能不让使用)
封装的级别:
共有的 public:成员面前什么都不加
受保护的 protected:在成员前面加一个_(下划线)
私有的 private:在成员前面加两个__(下划线)
public protected private
在类的内部 OK OK OK
在类的外部 OK No(python可以) No
注意:允许在外部访问受保护的成员,但是编译器会提示你正在访问受保护成员,不建议这么做
了解即可:python中成员的私有化就是概率成员的名字 _类名__成员
可以使用特殊语法从外部访问类的私有成员 对象._类型__成员
获取对象的所有成员:
对象.__dict__:获取当前对象(不包含类的)的所有成员信息
类.__dict__:获取当前类的所有成员信息
"""
class Person:
name = None
_age = None
__sanwei = None
def __init__(self,n,a,s):
self.name = n
self._age = a
self.__sanwei = s
def say(self):
print("say****************************************")
def sing(self):
print("sing****************************************")
def dance(self):
print(f"__sanwei = {self.__sanwei} --- dance***************************************")
lili = Person('lili',23,"60 50 60")
# 查看对象和类的所有成员
print(f"lili.__dict__ = {lili.__dict__}")
print(f"Person.__dict__ = {Person.__dict__}")
print(f"lili.__dir__() = {lili.__dir__()}")
print(f"lili.name = {lili.name}")
print(f"lili._age = {lili._age}") # 允许在外部访问受保护的成员,但是编译器会提示你正在访问受保护成员,不建议这么做
# print(f"lili.__sanwei = {lili.__sanwei}") # not allowed
lili.dance()
print(f"lili._Person__sanwei = {lili._Person__sanwei}") # 这种语法可以访问对象的私有成员,但是要尽量遵循规则
运行结果:
E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_5packaging.py
lili.__dict__ = {'name': 'lili', '_age': 23, '_Person__sanwei': '60 50 60'}
Person.__dict__ = {'__module__': '__main__', 'name': None, '_age': None, '_Person__sanwei': None, '__init__': <function Person.__init__ at 0x000001EECA8491F0>, 'say': <function Person.say at 0x000001EECA849040>, 'sing': <function Person.sing at 0x000001EECA849280>, 'dance': <function Person.dance at 0x000001EECA849310>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
lili.__dir__() = ['name', '_age', '_Person__sanwei', '__module__', '__init__', 'say', 'sing', 'dance', '__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__']
lili.name = lili
lili._age = 23
__sanwei = 60 50 60 --- dance***************************************
lili._Person__sanwei = 60 50 60
Process finished with exit code 0