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: **
__ field was renamed to _className__field by the compiler
Obj.__field cannot be accessed outside the class, but inside the class
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