Scope
Students who have studied Java all know that Java classes can define public (public) or private (private) methods and properties. This is mainly because we hope that some functions and properties can be used by others or For internal use only. By learning about modules in Python, they are actually similar to classes in Java. So how do we realize that in a module, some functions and variables are used by others, and some functions and variables are only used inside the module?
In Python, this is achieved through the _ prefix. Normal function and variable names are public and can be directly referenced, such as: abc, ni12, PI, etc.; variables like __xxx__ are special variables and can be directly referenced, but have special purposes, such as the above The __name__ is a special variable, and __author__ is also a special variable, used to indicate the author. Note that we generally do not use this type of variable name for our own variables; functions or variables like _xxx and __xxx are private and should not be directly referenced, such as _abc, __abc, etc.;
Note, this says shouldn’t, not cannot. Because there is no way in Python to completely restrict access to private functions or variables, however, private functions or variables should not be referenced from programming habits.
For example:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- def _diamond_vip(lv): print('尊敬的钻石会员用户,您好') vip_name = 'DiamondVIP' + str(lv) return vip_name def _gold_vip(lv): print('尊敬的黄金会员用户,您好') vip_name = 'GoldVIP' + str(lv) return vip_name def vip_lv_name(lv): if lv == 1: print(_gold_vip(lv)) elif lv == 2: print(_diamond_vip(lv)) vip_lv_name(2)
Output result:
尊敬的钻石会员用户,您好 DiamondVIP2
In this module, we expose the vip_lv_name method function, while other internal logic is in _diamond_vip and _gold_vip private respectively Implemented in the function, because it is an internal implementation logic, the caller does not need to care about this function method at all. It only needs to care about the method function that calls vip_lv_name, so using private is a very useful code encapsulation and abstract method.
General In this case, all functions that do not need to be referenced from the outside are defined as private, and only functions that need to be referenced from the outside are defined as public.