程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

No action, no intention Python object-oriented-51. Private member variables (encapsulation of data in classes)

編輯:Python

Catalog
  • 1、 Introduction to private member variables
    • (1) The concept of private member variables
    • (2) Characteristics of private member variables
    • (3) Private member variable experience
  • 2、 How property privatization works
  • 3、 Defines the identifier specification for member variables
  • 4、 How to get and set private member variables

1、 Introduction to private member variables

(1) The concept of private member variables

stay Python Object oriented , Some properties of the class , If in use , Don't want to be directly accessed by the outside world , You can set this property to private , That is, only the current class holds , Then expose to the outside world an access function , To achieve indirect access to object properties , This is the encapsulation of data in the class .

If the properties in the class do not want to be directly accessed by the outside world , You can add two underscores in front of the attribute __, In this case, this property is called private property , That is, private member variables .

The essence of encapsulation : Is the privatization of attributes .

(2) Characteristics of private member variables

Can only be accessed directly inside a class , Not directly accessible from the outside .

(3) Private member variable experience

1) Property is not privatized :

# 1. When properties are not privatized
class Student():
def __init__(self, name, age):
self.name = name
self.age = age
def tellMe(self):
print(f" Hello everyone , I am a {self.name}, Age {self.age}")
# Create objects
stu = Student(" The Monkey King ", 18)
# Through object . Member functions , Call the function and access the member variables in the object
stu.tellMe()
# Through object . attribute , Directly access the properties in the object
print(f" Hello everyone , I am a {stu.name}, Age {stu.age}")
# Directly access the properties of an object through an object , And assign a value to the property
stu.name = " Monkey King "
print(stu.name) # Monkey King
"""
Output results :
Hello everyone , I'm the monkey king , Age 18
Hello everyone , I'm the monkey king , Age 18
Monkey King
As you can see, you can access .
"""

2) Property is privatized :

# 2. When the property is privatized
class Student():
def __init__(self, name, age):
self.name = name
# Privatization age attribute
self.__age = age
def tellMe(self):
print(f" Hello everyone , I am a {self.name}, Age {self.__age}")
# Create objects
stu = Student(" The Monkey King ", 18)
# Through object . Member functions , Call the function and access the member variables in the object
# You can access the private member variables in the current object
# Output : Hello everyone , I'm the monkey king , Age 18
stu.tellMe()
# Through object . attribute , Directly access the properties in the object
# Report errors :
# AttributeError: 'Student' object has no attribute '__age'
# print(f" Hello everyone , I am a {stu.name}, Age {stu.__age}")
# Directly through the object . attribute , Modify the attribute value of member variable
# Sure
stu.name = " Monkey King "
print(stu.name) # Monkey King
# result : Hello everyone , I'm the saint of heaven , Age 18
stu.tellMe()
# Directly through the object . attribute , Modify the property value of private member variable
# Output results
stu.__age = 30
print(stu.__age) # 30
# result : Hello everyone , I'm the saint of heaven , Age 18
# But by calling methods in the object , View the private properties of the object
# The results have not changed , still 18
stu.tellMe()
"""
But we go through __dict__ Property view stu All members of the object :
{'name': ' Monkey King ', '_Student__age': 18, '__age': 30}
You can see that we have not modified the original properties '_Student__age': 18,
But to stu Object adds a new attribute '__age': 30.
So we don't have private member variables age Reassignment succeeded .
Only '_Student__age': 18 Why do you mean private variables age,
We will explain the principle of private members below .
"""
print(stu.__dict__)

explain : Properties starting with double underscores , Is a hidden property of an object , Hidden properties can only be accessed inside a class , Cannot access through object

2、 How property privatization works

class Student():
def __init__(self, name, age):
self.name = name
# Privatize member properties
self.__age = age
def tellMe(self):
print(f" Hello everyone , I am a {self.name}, Age {self.__age}")
"""
Actually hide ( Privatization ) Attributes are just Python Automatically changed a name for the property
It's actually changing the name to ,_ Class name __ Property name
such as __age -> _Student__name,
That is to add... Before the original variable name _ Class name .
"""
# Create objects
stu = Student(" The Monkey King ", 18)
# result : Hello everyone , I'm the monkey king , Age 18
stu.tellMe()
# Directly through the object . attribute , Modify the private member variable of the object
# You can see from the print results below , The modification was successful
stu._Student__age = 30
# result : Hello everyone , I'm the monkey king , Age 30
stu.tellMe()

summary :

Python in , did not The real meaning Of private , In fact, some special processing has been done for the name of member variables , Make it inaccessible to the outside world .

So it is defined as double underline __ The properties of the beginning , In fact, it can still be accessed externally .

But we usually don't recommend accessing private properties like this .

3、 Defines the identifier specification for member variables

  • xxx: Common variables .
  • _xxx: Use _ The first attribute is a protected variable , Do not modify without special needs .
  • __xxx: Use double _ The first attribute is a private variable , Not directly accessible from the outside .
  • __xxx__: Built in variables of the system .
  • xx_: Single post underline , Used to avoid and Python Keywords conflict .

Example :

class Student():
def __init__(self, name, age, gender):
# Add an underscore in front of the variable , It belongs to a special variable , The variable is considered protected
self._name = name
# Add a double underline before the variable . Represents the definition of private variables .
# characteristic : Object cannot be used directly
self.__age = age
# Add two underscores before and after the variable , It belongs to a special variable , It is generally believed that such variables are built-in variables or built-in functions of the system
# characteristic : You can also directly access... Outside the class , But not recommended
self.__gender__ = gender
stu = Student(" Tang's monk ", 66, " male ")
print(stu._name) # Tang's monk
print(stu.__gender__) # male

4、 How to get and set private member variables

(1) The way :

How to get ( modify ) Private properties in the object ?

Need to provide a getter() and setter() Method enables external access to properties .

  • getter() Method is used to get the specified property in the object .
    getter() The specification of the method is named get_ Property name .

  • setter() Method is used to set the specified property in the object .
    setter() The specification of the method is named set_ Property name .

(2) Format :

getter() Method : There will be a return value .

 def get_xxx(self):
return self. Property name

setter() Method : no return value , But the method has one more parameter .

def set_xxx(self, Parameter name ):
self. Property name = The value of the parameter name

(3) Example :

class Student():
def __init__(self, name, age):
# Common variables
self.name = name
# Private variables
self.__age = age
def tellMe(self):
print(f" Hello everyone , I am a {self.name}, Age {self.__age}")
def get_name(self):
"""
get_name() To get objects name attribute
"""
return self.name
def set_name(self, name):
"""
set_name() Used to set the object's name attribute
"""
self.name = name
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
# Create objects
stu = Student(" The Monkey King ", 18)
# Output results : Hello everyone , I'm the monkey king , Age 18
stu.tellMe()
# Modify attribute values
stu.set_name(" Monkey King ")
stu.set_age(30)
# Print attribute values
# The result is : Hello everyone , I'm the saint of heaven , Age 30
stu.tellMe()
print(f" Hello everyone , I am a {stu.get_name()}, Age {stu.get_age()}")
"""
Private attributes can only be used inside a class , Object cannot be used directly , But we can call or modify private properties by defining public methods inside the class , Then the object uses... When calling the public method
"""

(4) summary :

  • Both ordinary and private methods can be used getter() Methods and setter() Method to get or set the property value , We often program like this in our daily development .
  • Using encapsulation , It does increase the complexity of the class definition , But it also ensures data security .
  • Added getter() Methods and setter() Method , It's a good way to control whether a property is read-only ,
    If you want the property to be read-only , It can be removed directly setter() Method ,
    If you want properties to be inaccessible from the outside , It can be removed directly getter() Method .
  • Use setter() Method to set properties , You can add data validation , Make sure the value of the data is correct , Such as :
     def set_age(self, age):
    if age > 0:
    self.__age = age
    
  • The same use getter() Method to get properties , Or use setter() Method to set properties , You can read and modify properties at the same time , Do some other processing of the data .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved