How to define private attributes in Python

Python does not have a private keyword similar to Java, but you can also define private attributes for classes. Just change the attribute name to start with __, such as __field.

Sample code:

classVector2D(object):
 def __init__(self, x, y):
 self.__x =float(x)
 self.__y =float(y)
 self.xx = x
 self.yy = y 
 def get_x(self):return self.__x #Internal access
if __name__ =="__main__":
 v =Vector2D(3,4)
 print v.__dict__
 print v._Vector2D__x, v.get_x()#But you can pass v._Vector2D__x External access
 v.__x #External access

Output:

{' yy':4,'xx':3,'_Vector2D__x':3.0,'_Vector2D__y':4.0}3.03.0Traceback(most recent call last):...
v.__x
AttributeError:'Vector2D' object has no attribute '__x'

**As can be seen from the above example: **

  1. __ field was renamed to _className__field by the compiler

  2. Obj.__field cannot be accessed outside the class, but inside the class

  3. However, this can only prevent inadvertent calls, not malicious calls. In the words of Fluent Python, this is a safety device, not security device. In Mandarin, it is to prevent gentlemen from xx, because you can pass obj ._className__field accesses obj's private __field externally.

Supplementary knowledge: private attributes and private methods in python, modify the value of private attributes

If an attribute starts with two underscores, it indicates that this attribute is a private attribute

self.__money = 1000000

If a method starts with two underscores, it also means it is private

The child class inherits the parent class if the properties of the parent class are private, it will not be inherited by the child class

Private properties and private methods can be used in the class

If an attribute in a custom class is private, it cannot be called outside the class

Modify the value of a private attribute

If you need to modify the attribute value of an object, there are usually two methods

Object name. Attribute name = data — direct modification
Object name. Method name () --- indirect modification

Private attributes cannot be accessed directly, so they cannot be modified in the first way. Generally, the value of private attributes is modified in the second way: define a public method that can be called, and access and modify it in this public method.

classPerson(object):
 
 def __init__(self):
 self.name ="Xiao Ming"
 self.__age =20
 
 # Get the value of a private property
 def get_age(self):return self.__age
 
 # Set the value of a private property
 def set_age(self, new_age):
 self.__age = new_age
 
 
# Define an object
p =Person()
# Forcibly obtain private properties
# Advocating everything depends on consciousness
print(p._Person__age)print(p.name)
# Want to get the properties of the object outside the class
ret = p.get_age()print(ret)
 
# Want to modify the value of the private property of the object outside the class
p.set_age(30)print(p.get_age())

The above definition of private attributes in Python is all the content shared by the editor, I hope to give you a reference.

Recommended Posts

How to define private attributes in Python
How to wrap in python code
How to omit parentheses in Python
How to write classes in python
How to filter numbers in python
How to read Excel in Python
How to view errors in python
How to write return in python
How to understand variables in Python
How to clear variables in python
How to use SQLite in Python
How to use and and or in Python
How to delete cache files in python
How to introduce third-party modules in Python
How to represent null values in python
How to save text files in python
How to run id function in python
How to install third-party modules in Python
How to custom catch errors in python
How to write try statement in python
How to add custom modules in Python
How to understand global variables in Python
How to view installed modules in python
How to open python in different systems
How to sort a dictionary in python
How to add background music in python
How to represent relative path in python
How to use the round function in python
How to use the zip function in Python
How to program based on interfaces in Python
How to install python in ubuntu server environment
How to simulate gravity in a Python game
How to use the format function in python
How to use code running assistant in python
How to set code auto prompt in python
Teach you how to write games in python
How to delete files and directories in python
How to install the downloaded module in python
How to write a confession program in python
How to perform continuous multiplication calculation in python
How to comment python code
How to learn python quickly
How to uninstall python plugin
How to understand the introduction of packages in Python
How to understand a list of numbers in python
Example of how to automatically download pictures in python
How to save IE as an attachment in python
How to understand python objects
How to use python tuples
How to create a Python virtual environment in Ubuntu 14.04
How to find the area of a circle in python
Do you still know how to draw cakes in python? ? ?
How to install Helm in Ubuntu
python how to view webpage code
How to use hanlp in ubuntu
How to use python thread pool
How to write python configuration file
How to install PHP7.4 in CentOS
How to save the python program
How to install mysql in Ubuntu 14.04
How to install Python 3.8 on CentOS 8