In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "Python private functions, private variables and encapsulation methods", so the editor summarizes the following contents, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python private functions, private variables and encapsulation methods" article.
What are private functions and private variables
What do private functions and private variables mean? To understand simply means to own, not to disclose, and not to share. Put into functions and variables are independently owned functions and independently owned variables, and are not disclosed. In this way, we understand what private functions and private variables are.
Functions and variables in a class that cannot be called by an instantiated object
Although it cannot be called by the instantiated object, we can call private functions and private variables inside the class.
The purpose of private functions and private variables: you only want to be used by business calls within the class, not by instantiated object calls.
Since there are private functions and private variables, the functions and variables that can be called by instantiated objects are public functions and public variables, but we generally call them functions and variables.
The definition of Private function and Private variable
How to define private functions and private variables: add _ (2 underscores) before class variables and class functions to define private functions and private variables; variables or functions do not need to be added after, there are two underscores left and right, which is the definition specification of the built-in function of the class.
Examples of private functions and private variables are as follows:
Class Persion (object): def _ init__ (self): self.name = name self.__age = 18 # 'self.__age' is the private variable of the Persion class def run (self): print (self.name, self.__age) # in the code block of the Persion class Private variables can still be called def _ _ eat (self): #'_ _ eat (self)'is the Persion private function return'I want eat some fruits'
Next, let's make some changes according to the sample code above to better demonstrate private functions and private variables to facilitate a deeper understanding.
Class PersionInfo (object): def _ _ init__ (self Name): self.name = name def eat (self): result = self.__eat () print (result) def _ eat (self): return f'{self.name} favorite fruits are\ 'durian\' and\ 'guava\' def run (self): result = self.__run () print (result) def _ _ run (self): return f' {self.name} favorite fitness methods are\ 'running\' and\ 'swimming\' 'persion = PersionInfo (name='Neo') persion.eat () persion.run () # > the results are as follows: # > Neo's favorite fruits are durian and guava. Neo's favorite fitness methods are running and swimming
Let's try again to call the _ _ eat private function through the instantiated object persion
Class PersionInfo (object): def _ _ init__ (self Name): self.name = name def eat (self): result = self.__eat () print (result) def _ eat (self): return f'{self.name} favorite fruits are\ 'durian\' and\ 'guava\' def run (self): result = self.__run () print (result) def _ _ run (self): return f'{self.name} favorite fitness methods are\ 'running\' and\ 'swimming\' 'persion = PersionInfo (name='Neo') persion.__eat () # > the execution result is as follows: # > > AttributeError:' PersionInfo' object has no attribute'_ eat'# > once again, it is proved that instantiated objects cannot call private functions.
So is it true that there is no way to call private functions if the object is instantiated? Actually, it's not. Let's move on.
Class PersionInfo (object): def _ _ init__ (self Name): self.name = name def eat (self): result = self.__eat () print (result) def _ eat (self): return f'{self.name} favorite fruits are\ 'durian\' and\ 'guava\' def run (self): result = self.__run () print (result) def _ _ run (self): return f'{self.name} favorite fitness methods are\ 'running\' and\ 'swimming\' persion = PersionInfo (name='Neo') # check what functions are available in the instantiated object persion through the dir () function? Print (dir (persion))
You can see that the instantiated object persion also has two private variables, _ Persion__eat and _ Persion__run, so try to call the private variable directly with the instantiated object persion.
Class PersionInfo (object): def _ _ init__ (self Name): self.name = name def eat (self): result = self.__eat () print (result) def _ eat (self): return f'{self.name} favorite fruits are\ 'durian\' and\ 'guava\' def run (self): result = self.__run () print (result) def _ _ run (self): return f'{self.name} favorite fitness methods are\ 'running\' and\ 'swimming\' persion = PersionInfo (name='Neo') # check what functions are available in the instantiated object persion through the dir () function? Print (dir (persion)) print (persion._PersionInfo__eat ()) print (persion._PersionInfo__run ()) # > the execution result is as follows:
You can see that in this way, our instantiated object persion also successfully calls the private function of the PersionInfo class; but since it is a private function, the purpose is not to be called by the instantiated object, so we'd better use it according to the coding specification.
Attachment: the use of private variables (private attributes) is the same as private functions, let's take a look at the following example
Class PersionInfo (object): _ _ car = 'BMW' def _ init__ (self, name, sex): self.name = name self.__sex = sex def info (self): result = self.__info () print (result) def _ info (self): return f' {self.name} gender: {self.__sex} He has one:\'{self.__car}\ 'persion = PersionInfo (name='Neo', sex=' male) persion.info () # > > the execution result is as follows: # > > Neo gender: male, he has one:' BMW'# > try to call private functions private functions and variables (attributes) ['_ PersionInfo_01__car','_ PersionInfo_01__info' '_ PersionInfo_01__sex'] print (persion01._PersionInfo_01__info ()) # > the execution result is as follows: # > Neo gender: male, he has one: package in BMW'Python
In fact, this function is not encapsulated in Python, but encapsulation is just a concept for a certain business scenario in Python.
The concept of encapsulation-> uses private properties or methods that are not external through functions that can be used externally (private functions and private methods defined in the class can only be used inside the class, but cannot be accessed externally). The main reason for this is to protect privacy and make a clear distinction between inside and outside.
Examples of encapsulation are as follows:
Class Persion (object): def _ _ hello (self Data): print ('hello% s'% data) def helloworld (self): self.__hello ('world') if _ name__ =' _ main__' persion = Persion () persion.helloworld () # > the execution result is as follows: # > helloworld # > > We can see that helloworld () is executed based on the private function _ _ hello () # > so we call the internal private function _ _ hello through the external function helloworld (); this is the concept of encapsulation in Python. Small exercises in object-oriented programming
Demand:
Use classes and objects to manage capital transactions in bank accounts, including deposits, withdrawals and printing transaction details, including the time of each transaction, the amount of deposits or withdrawals, and the balance after each transaction.
Examples of scripts are as follows:
# coding: utf-8import timeclass MoneyExchange (object): money = 0 abstract = [] single_bill_list = [] bill_list = [] transcation_num = 0 currency_type = "RMB" service_option_num = [] service_option = [] service_menu = {1: "1: deposit", 2: "2: withdrawal", 3: "3: view details" 4: "4: check the balance", 0: "0: exit the system"} for key, value in service_menu.items (): service_option_num.append (key) service_option.append (value) def welcome_menu (self): print ('* 20 + 'Welcome to the fund transaction management system' +'*) for i in range (0 Len (self.service_option): print (self.service_ option [I]) print ('*'* 60) def save_money (self): self.money_to_be_save = float (input ('Please enter the deposit amount:') self.abstract = 'transferred' self.time = time.strftime ("% Y-%m-%d% H:%M:%S" Time.localtime () self.money + = self.money_to_be_save self.single_bill_list.append (self.time) self.single_bill_list.append (self.abstract) self.single_bill_list.append (self.money_to_be_save) self.single_bill_list.append (self.currency_type) self.single_bill_list.append (self.money) Self.bill_list.append (self.single_bill_list) self.single_bill_list = [] self.transcation_num + = 1 print ('successfully deposited! The current balance is:% s yuan'% self.money) input ('Please click any key to continue.') Def withdraw_money (self): self.money_to_be_withdraw = float (input ('Please enter the withdrawal amount:) if self.money_to_be_withdraw > > the execution result is as follows: # > * Welcome to the fund transaction management system * # > 1: apply Deposit # > 2: apply for withdrawal # > 3: check details # > > 4: check the balance # > 0: exit the system # > * * # > execute the corresponding operation according to the prompt above is about "Python private function" The content of this article "Private variables and encapsulated methods" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.