search
HomeBackend DevelopmentPython TutorialLet's talk about Python private properties and private methods

Let's talk about Python private properties and private methods

1. Scenario definition

Private attributes

means that in the object-oriented development process of Python, some attributes of the object are only available in the object are used internally, but do not want these properties to be accessed externally.

That is: private attributes are attributes that the object is not willing to make public.

Private methods

means that in the object-oriented development process of Python, some methods or functions of the object only want to be used inside the object, but do not want to be accessed externally. these methods or functions.

That is: a private method is a method or function that the object does not want to make public.

2. Syntax definition

The syntax for defining private properties and private methods in Python is as follows:

class Staff:
def __init__(self, s_name, s_salary):
self.s_name = s_name
self.__salary = s_salary

def __secret(self):
print("%s 的工资是 %d" % (self.s_name, self.__salary))

(1). __salary is defined starting with two underscores Private property.

(2). __secret(self) is a private method defined starting with two underscores.

3. Call analysis

(1). In the object initialization method of __init__, the __salary attribute defined starting with two underscores is a private attribute.

Now call the __salary attribute outside the object to see if the private attribute can be accessed normally.

Let's talk about Python private properties and private methods

As can be seen from the running results in the above figure, line 11, that is, when accessing the private attribute __salary of the object outside the object, an AttributeError error is prompted, and the Staff object zhangsan has no attributes. __salary.

In order to prove that the Staff class object does have the instance attribute __salary, it is just because the private attributes cannot be accessed outside the object.

I modified self.__salary to: self.salary, the __secret(self) method references the self.__salary attribute, and made corresponding modifications. See the running results as shown in the figure below.

Let's talk about Python private properties and private methods

It can be seen from the running results that the external call of this non-private attribute is normal and no AttributeError error is prompted.

(2). In the __secret(self) instance method, the __secret(self) method defined starting with two underscores is a private method.

Same as the above test process, first call the private method __secret(self) outside the object to see if the private method can be called normally.

Let's talk about Python private properties and private methods

As can be seen from the running results in the above figure, line 11, that is, when accessing the private method __secret(self) of the object outside the object, an AttributeError error is prompted, the Staff object zhangsan does not have a __secret method.

To prove that the Staff class object has the instance method __secret(self), just because the private method cannot be accessed outside the object.

I modified the __secret(self) method to: secret(self), and other codes remain unchanged. See the running results as shown in the figure below.

Let's talk about Python private properties and private methods

It can be seen from the running results that the external call of this non-private method is normal and no AttributeError error is prompted.

(3). As can be seen from the figure below, private methods and private properties can be called inside the object.

The work method in the figure calls the private method __secret(self), and the private method __secret(self) calls the private attribute __salary.

Let's talk about Python private properties and private methods

Use the Staff class object zhangsan outside the object to call the work method, which can indirectly access the private properties and private methods of the object.

From the console output, it can be seen that the work method can normally access the private properties and private methods defined inside the object.

4. Python pseudo-private properties and private methods

In Python, there is no real sense of privateness, because Python internally makes some special names when naming properties and methods. Processing makes the corresponding properties and methods inaccessible to the outside world.

Taking private attributes and private methods as an example, Python’s internal processing method is:

(1). Attribute: __salary, the processed attribute name is: _Staff__salary(_class name__ Attribute name)

(2). Method: __secret, the processed method name is: _Staff__secret(_class name__method name)

I know Python internally for private attributes and private Method processing, now use this processed naming method to access private properties and private methods outside the object to see if the access is normal.

class Staff:
def __init__(self, s_name, s_salary):
self.s_name = s_name
self.__salary = s_salary

def __secret(self):
return "%s的工资是 %d" % (self.s_name, self.__salary)
zhangsan = Staff("张三", 10000)
print(zhangsan._Staff__salary)
print(zhangsan._Staff__secret())

The running results are shown in the figure below

Let's talk about Python private properties and private methods

The console did not throw any exceptions, and the previous AttributeError error message disappeared.

This example proves that Python is not private in the true sense. After knowing its internal processing method, you can still use the _class name__ attribute name (method name) method to access outside the object. To the private properties and private methods defined inside the object.

But this method is not recommended in daily work. Since when properties and methods are defined inside the object, they are declared private, and the caller needs to abide by its rules.

I just want to use this small example to illustrate that Python does not have real privacy.

The above is the detailed content of Let's talk about Python private properties and private methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),