網站首頁 編程語言 正文
一、_func 單下劃線開頭 --口頭私有變量
1.1、在模塊中使用單下劃線開頭
在Python中,通過單下劃線_來實現模塊級別的私有化,變量除外。一般約定以單下劃線開頭的函數為模塊私有的,也就是說from moduleName import * 將不會引入以單下劃線開頭的函數。模塊中使用單下劃線開頭定義函數、全局變量和類均適用,但可以用:from module import _func形式單獨導入。
實例如下:
lerarn_under_line.py
# coding=utf-8
course = "math"
_credit = 4
def call_var():
? ? print "course:%s" % course
? ? print "_credit:%d" % _credit
def _call_var():
? ? print "帶下劃線course:%s" % course
? ? print "帶下劃線_credit:%d" % _credit
def __call_var():
? ? print "帶雙下劃線course:%s" % course
? ? print "帶雙下劃線_credit:%d" % _credit
import lerarn_under_line
>>> import lerarn_under_line
>>> lerarn_under_line.call_var
<function call_var at 0x10aa61850>
>>> lerarn_under_line.call_var()
course:math
_credit:4
>>> lerarn_under_line._call_var() ? # 單下劃線可以調用
帶下劃線course:math
帶下劃線_credit:4
>>> >>> lerarn_under_line.__call_var() ? # 雙下劃線不可調用
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__call_var'
from lerarn_under_line import *
>>> from lerarn_under_line import *
>>> course
'math'
>>> _credit
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name '_credit' is not defined
>>> call_var()
course:math
_credit:4
>>> _call_var()
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name '_call_var' is not defined
>>> __call_var()
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name '__call_var' is not defined
from module import _func
>>> from lerarn_under_line import course
>>> course
'math'
>>> from lerarn_under_line import _credit
>>> _credit
4
>>> from lerarn_under_line import call_var
>>> call_var()
course:math
_credit:4
>>> from lerarn_under_line import _call_var
>>> _call_var()
帶下劃線course:math
帶下劃線_credit:4
>>> from lerarn_under_line import __call_var
>>> __call_var()
帶雙下劃線course:math
帶雙下劃線_credit:4
1.2、在類中使用單下劃線開頭
lerarn_under_line.py
class Course(object):
? ? def __init__(self, name):
? ? ? ? self.name = name
? ? def credit(self):
? ? ? ? if self.name == 'math':
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 4)
? ? ? ? else:
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 2)
? ? def _credit(self):
? ? ? ? if self.name == 'math':
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 4)
? ? ? ? else:
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 2)
? ? def __credit(self):
? ? ? ? if self.name == 'math':
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 4)
? ? ? ? else:
? ? ? ? ? ? print "%s的credit 為%d" % (self.name, 2)
import lerarn_under_line
>>> import lerarn_under_line
>>> a=Course('math')
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
from lerarn_under_line import *
>>> from lerarn_under_line import *
>>> a=Course('math')
>>> a.credit()
math的credit 為4
>>> a._credit()
math的credit 為4
>>> a.__credit()
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__credit'
from lerarn_under_line import Course
>>> from lerarn_under_line import Course
>>> a=Course('math')
>>> a.__credit()
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__credit'
>>> a._credit()
math的credit 為4
>>> a.credit()
math的credit 為4
綜上,單下劃線開頭的函數表示是口頭實例私有變量,是可訪問的,但是也不要隨意訪問,即所謂防君子不防小人。
二、__func 雙下劃線開頭的函數 --私有變量
2.1、在模塊中使用雙下劃線開頭
在實例中,帶雙下劃線的類變量、實例變量、方法不能被直接訪問。但有辦法間接訪問。如1.1中的from module import __func
>>> from lerarn_under_line import *
>>> __call_var()
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name '__call_var' is not defined
>>> import lerarn_under_line
>>> lerarn_under_line.__call_var() ? # 雙下劃線不可調用
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__call_var'
>>> from lerarn_under_line import course
>>> from lerarn_under_line import __call_var
>>> __call_var()
帶雙下劃線course:math
帶雙下劃線_credit:4
2.2、在類中使用雙下劃線開頭
- 在class類的內部,帶雙下劃線的類變量、實例變量、方法具有正常訪問權限。
- 在繼承結構中,帶雙下劃線的基類的類變量和實例變量不能被子類直接訪問。
lerarn_under_line.py
class Course(object):
? ? def __init__(self, name, _teacher, __classroom):
? ? ? ? self.name = name
? ? ? ? self._teacher = _teacher
? ? ? ? self.__classroom = __classroom
? ? def call_var(self):
? ? ? ? print "name:%s" % self.name
? ? ? ? print "_teacher:%s" % self._teacher
? ? ? ? print "__classroom:%s" % self.__classroom ??
>>> import lerarn_under_line
>>> a = Course('math', 'zhangyu', 'juyiting') ?# 無法實例化
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> from lerarn_under_line import *
>>> a = Course('math', 'zhangyu', 'juyiting')
>>> a.call_var()
name:math
_teacher:zhangyu
__classroom:juyiting
lerarn_under_line.py
class Course(object):
? ? def __init__(self, name, _teacher, __classroom):
? ? ? ? self.name = name
? ? ? ? self._teacher = _teacher
? ? ? ? self.__classroom = __classroom
? ? def call_var(self):
? ? ? ? print "name:%s" % self.name
? ? ? ? print "_teacher:%s" % self._teacher
? ? ? ? print "__classroom:%s" % self.__classroom
class SonCourse(Course):
? ? def __init__(self, name, _teacher, __classroom, time):
? ? ? ? super(Course, self).__init__()
? ? ? ? self.time = time
? ? ? ? self.name = name
? ? ? ? self.__classroom = self.__classroom
? ? ? ? self._teacher = self._teacher
? ? ? ? self.__classroom = self.__classroom
? ? def call_son_var(self):
? ? ? ? print "time:%s" % self.time
? ? ? ? print "name:%s" % self.name
? ? ? ? print "_teacher:%s" % self._teacher
? ? ? ? print "__classroom:%s" % self.__classroom
>>> import lerarn_under_line
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
? File "lerarn_under_line.py", line 77, in <module>
? ? b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
? File "lerarn_under_line.py", line 63, in __init__
? ? self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'
>>> from lerarn_under_line import *
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
? File "lerarn_under_line.py", line 77, in <module>
? ? b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
? File "lerarn_under_line.py", line 63, in __init__
? ? self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'
>>> from lerarn_under_line import Course
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
? File "lerarn_under_line.py", line 77, in <module>
? ? b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
? File "lerarn_under_line.py", line 63, in __init__
? ? self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'
>>> from lerarn_under_line import sonCourse
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
? File "lerarn_under_line.py", line 77, in <module>
? ? b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
? File "lerarn_under_line.py", line 63, in __init__
? ? self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'
三、前后都有雙下劃線 --特殊變量
Python保留了有雙前導和雙末尾下劃線的名稱,用于特殊用途。 這樣的例子有,init__對象構造函數,或__call — 它使得一個對象可以被調用。這些方法通常被稱為神奇方法,最好避免在自己的程序中使用以雙下劃線開頭和結尾的名稱,以避免與將來Python語言的變化產生沖突。
常見方法:
方法 | 含義 |
---|---|
__str__ | 當將對象轉換成字符串時會執行 |
__init__ | 初始化方法,為對象變量賦值 |
__new__ | 構造方法,創建一個對象 |
__call__ | 在對象后面加括號會執行該方法 |
__getattr__ | 當使用對象.屬性時,若屬性不存在會調用該方法 |
__setattr__ | 當使用對象.屬性 = 值,會調用該方法 |
__iter__ | 類內部定義了該方法,對象就變成了可迭代對象 |
__add__ | 當兩個對象使用+號會調用該方法 |
__enter__和__exit__ | 上下文管理 |
參考文檔
1、https://blog.csdn.net/brucewong0516/article/details/79120841
2、http://t.zoukankan.com/one-tom-p-11749739.html
3、https://www.cnblogs.com/bryant24/p/11429653.html
4、https://blog.csdn.net/m0_58357932/article/details/121062461
5、https://www.likecs.com/show-308380836.html
原文鏈接:https://blog.csdn.net/yuelai_217/article/details/128706898
相關推薦
- 2023-07-04 spring boot security驗證碼登錄示例
- 2021-12-12 C/C++?Qt?數據庫QSql增刪改查組件應用教程_C 語言
- 2022-07-02 Pandas?如何處理DataFrame中的inf值_python
- 2024-02-26 Cannot execute binary file 之原因
- 2023-02-23 一文詳解C語言char類型中的存儲_C 語言
- 2022-03-11 CentOS?8安裝Docker的詳細教程_docker
- 2022-11-09 Golang中字符串(string)與字節數組([]byte)一行代碼互轉實例_Golang
- 2022-09-04 python?matplotlib庫繪圖實戰之繪制散點圖_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支