current position:Home>Python notes (11): encapsulation such as object-oriented programming

Python notes (11): encapsulation such as object-oriented programming

2022-01-30 12:38:32 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

The understanding of encapsulation

encapsulation (Encapsulation): Abstraction of properties and methods

  • Attribute abstraction : The properties of the class ( Variable ) Define 、 Isolation and protection

    It is divided into private attributes and public attributes

    • Private property : Can only be accessed inside a class
    • Public attributes : You can use the 、 Object name access

    You can choose to expose or hide properties , The internal mechanism of hiding attributes

  • Abstraction of methods : Methods for classes ( function ) Define 、 Isolation and protection

    It is divided into private methods and public methods

    • Private method : Can only be accessed inside a class
    • Open methods : You can use the 、 Object name access

    You can choose to expose or hide the method , Hide the internal logic of the method

  • The goal is to form an interface for externally operable properties and methods

Encapsulation is the process of making data and code called classes , Expressed as : class —— attribute —— Method

Private class properties 、 Expose class properties 、 Private instance properties and public instance properties

Expose class properties

Public class attributes are class attributes , Grammatical structure

class ClassName:
    < Class property name > = < Class attribute initial value >
    def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
        self.< Instance property name > = < Initial value of instance attribute >
    ...
 Copy code 

Private class properties

Private class properties can only be accessed by the current class , Subclass cannot access . Grammatical structure

class ClassName:
    <__ Private class property name > = < Initial value of property >
    def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
        self.< Instance property name > = < Initial value of instance attribute >
    ...
 Copy code 

.< Class properties > perhaps < Object name >.< Class properties > Mode of access

Effectively ensure the controllability of attribute maintenance

The sample code is as follows :

class TestClass:
    __number = 0

    def __init__(self, num_value):
        for i in range(num_value + 1):
            TestClass.__number += i

    @classmethod  #  Class method 
    def sum_number(cls):
        return TestClass.__number


value1 = TestClass(100)
print(TestClass.sum_number())  # 5050
# print(value1.__number)  # AttributeError: 'TestClass' object has no attribute '__number'
 Copy code 

In class takeout visit .__number Will report AttributeError abnormal

Expose instance properties

Exposing the instance property is equal to the instance property , Grammatical structure

class < Class name >:
    < Class property name > = < Class method value >
    def __init__(self, < parameter list >):
        self.< Instance property name > = < Instance property value >
    ...
 Copy code 

Private instance properties

Private instance properties can only be used inside the current class , Subclasses cannot use . Grammatical structure

class < Class name >:
    < Class property name > = < Class method value >
    def __init__(self, < parameter list >):
        self.<__ Private instance property name > = < Instance property value >
    ...
 Copy code 

.< Class properties > perhaps < Object name >.< Class properties > Mode of access

Effectively ensure the controllability of attribute maintenance

Sample code

class TestClass:

    def __init__(self, num_value):
        self.__number = 0
        for i in range(num_value + 1):
            self.__number += i

    def sum_number(self):
        return self.__number


value1 = TestClass(100)
print(value1.sum_number())  # 5050
# print(value1.__number)  # AttributeError: 'TestClass' object has no attribute '__number'
 Copy code 

Private attributes are not necessarily really private

The double underline of private attributes is just a conversion Convention , After the transformation , The original name in the class has changed , This is a formal private

Sample code

class TestClass:

    def __init__(self, num_value):
        self.__number = 0
        for i in range(num_value + 1):
            self.__number += i

    def sum_number(self):
        return self.__number


value1 = TestClass(100)
print(value1.sum_number())  # 5050
print(value1._TestClass__number)  # 5050
#  Can pass   Object name ._ Class name __ attribute   The way to access 
 Copy code 

Can pass Object name ._ Class name __ attribute The way to access .

Private methods and public methods

Defining a method is a method defined and used inside a class . Grammatical structure

class < Class name >:
    def <__ Private method name >(self, < parameter list >):
        ...
 Copy code 

When defining a private method, two underscores are required in front of the attribute name (__).

All kinds of methods can change the method into private method by adding double down line change

Private methods formally protect Python The function logic used inside the class

Private attributes and disclosure are programmer logic , Not security logic , Pay attention to the agreement

Reserved properties of class

Python Class properties reserved by the interpreter , Start or end with double down lines .

  • Reserved attributes are also called special attributes
  • Start and end with a double underscore
  • The function is to understand Python Class provides a unified attribute interface
  • Attribute values have special meanings , Use directly after class definition

Just use < Class name > Access reserved properties

Keep attributes describe
__name__ Noun of class
__qualname__ With . Separate class names starting from the template global namespace
__bases__ The name of the base class inherited by the class

Class's reserved methods

The retention method is Python Method reserved by interpreter , Start and end with a double underscore

  • The retention method is also called special method
  • Start and end with a double underscore
  • The function is to understand Python Class provides a unified method interface
  • Method logic : It has a specific meaning , Generally associated with operators , Class definitions need to be overloaded

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301238288443.html

Random recommended