📜  Python中的封装

📅  最后修改于: 2022-05-13 01:55:37.295000             🧑  作者: Mango

Python中的封装

封装是面向对象编程(OOP)中的基本概念之一。它描述了包装数据的想法以及在一个单元内处理数据的方法。这限制了直接访问变量和方法,并且可以防止意外修改数据。为防止意外更改,对象的变量只能通过对象的方法进行更改。这些类型的变量称为私有变量。

类是封装的一个例子,因为它封装了成员函数、变量等所有数据。

考虑一个真实的封装示例,在公司中,有不同的部分,如账户部分、财务部分、销售部分等。财务部分处理所有财务交易并记录与财务相关的所有数据。同样,销售部分处理所有与销售相关的活动并保存所有销售记录。现在可能会出现一种情况,财务部门的官员出于某种原因需要有关特定月份的所有销售数据。在这种情况下,不允许他直接访问销售部分的数据。他首先必须联系销售部门的其他官员,然后要求他提供具体数据。这就是封装。在这里,销售部门的数据和可以操作它们的员工被包装在一个单一的名称“销售部门”下。使用封装也会隐藏数据。在此示例中,销售、财务或帐户等部分的数据对任何其他部分都是隐藏的。

受保护的成员

受保护的成员(在 C++ 和Java中)是那些不能在类外访问但可以从类及其子类内部访问的成员。要在Python中完成此操作,只需按照约定在成员名称前加上一个下划线“_”即可。

尽管受保护的变量可以从类外访问,也可以在派生类中访问(在派生类中也可以修改),但习惯上(约定不是规则)不访问受保护的类主体。

注意: __init__ 方法是一个构造函数,并在类的对象被实例化后立即运行。

Python3
# Python program to
# demonstrate protected members
 
# Creating a base class
class Base:
    def __init__(self):
 
        # Protected member
        self._a = 2
 
# Creating a derived class
class Derived(Base):
    def __init__(self):
 
        # Calling constructor of
        # Base class
        Base.__init__(self)
        print("Calling protected member of base class: ",
              self._a)
 
        # Modify the protected variable:
        self._a = 3
        print("Calling modified protected member outside class: ",
              self._a)
 
 
obj1 = Derived()
 
obj2 = Base()
 
# Calling protected member
# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)
 
# Accessing the protected variable outside
print("Accessing protected member of obj2: ", obj2._a)


Python3
# Python program to
# demonstrate private members
 
# Creating a Base class
 
 
class Base:
    def __init__(self):
        self.a = "GeeksforGeeks"
        self.__c = "GeeksforGeeks"
 
# Creating a derived class
class Derived(Base):
    def __init__(self):
 
        # Calling constructor of
        # Base class
        Base.__init__(self)
        print("Calling private member of base class: ")
        print(self.__c)
 
 
# Driver code
obj1 = Base()
print(obj1.a)
 
# Uncommenting print(obj1.c) will
# raise an AttributeError
 
# Uncommenting obj2 = Derived() will
# also raise an AtrributeError as
# private member of base class
# is called inside derived class


输出:

Calling protected member of base class:  2
Calling modified protected member outside class:  3
Accessing protected member of obj1:  3
Accessing protected member of obj2:  2

私人会员

私有成员类似于受保护成员,不同之处在于声明为私有的类成员既不能在类外访问,也不能被任何基类访问。在Python中,不存在只能在类内部访问的Private实例变量。

但是,要定义私有成员,请在成员名称前加上双下划线“__”。

注意: Python 的私有成员和受保护成员可以通过Python名称修饰在类外部访问。

Python3

# Python program to
# demonstrate private members
 
# Creating a Base class
 
 
class Base:
    def __init__(self):
        self.a = "GeeksforGeeks"
        self.__c = "GeeksforGeeks"
 
# Creating a derived class
class Derived(Base):
    def __init__(self):
 
        # Calling constructor of
        # Base class
        Base.__init__(self)
        print("Calling private member of base class: ")
        print(self.__c)
 
 
# Driver code
obj1 = Base()
print(obj1.a)
 
# Uncommenting print(obj1.c) will
# raise an AttributeError
 
# Uncommenting obj2 = Derived() will
# also raise an AtrributeError as
# private member of base class
# is called inside derived class

输出:

GeeksforGeeks
Traceback (most recent call last):
  File "/home/f4905b43bfcf29567e360c709d3c52bd.py", line 25, in 
    print(obj1.c)
AttributeError: 'Base' object has no attribute 'c'

Traceback (most recent call last):
  File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27, in 
    obj2 = Derived()
  File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20, in __init__
    print(self.__c)
AttributeError: 'Derived' object has no attribute '_Derived__c'