python 基礎 5.4 類的私有屬性和私有方法


一. 類的私有變量和私有方法
1》   在python 中可以通過在屬性變量名前,加上雙下划線定義屬性為私有屬性
 
2》特殊變量命名
a. _xx 以單下划線開頭的表示的是protected(受保護的) 類型的變量,即保護類型只能靠允許其本身與子類進行訪問。若內部變量表示,如:當使用“from M import” 時,不會將一個下划線開頭的對象引入。
 
b.__xx  雙下划線的表示的是私有類型的變量。只能允許這個類本身進行訪問了,連子類也不可以用於命名一個類屬性(類變量),調用時名字被改變(在類 FooBar 內部,__boo 變成 __FooBar__boo,如self.__FooBar__boo)
 
c. 私有變量實例:
#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/7 8:40
#@Auther :liuzhenchuan
#@File   :類的私有變量.py
 
class A(object):
   '''類的私有變量和私有屬性'''
    _name = 'liuzhenchuan'
    __sex = 'F'
    def hello(self):
        print self._name
        print self.__sex
    def get_sex(self):
        return self.__sex
a = A()
#
print a._name
#私有變量 __sex 只能在類中被調用,實例化之前的部分是類中,單獨調用 a.__sex 報錯
# print a.__sex
#私有變量 __sex 可以在自己的方法中調用
a.hello()
#可以把私有變量定義一個方法,進行調用
print a.get_sex()
 
print '##'*5 + '子類' + '##'*5
 
class B(A):
    coller = 'yellow'
    def get_coller(self):
        return self.coller
b = B()
print b.coller
#父類中保護類型變量 _name 在子類中可以被調用
print b._name
 
>>>
liuzhenchuan
liuzhenchuan
F
F
##########子類##########
yellow
liuzhenchuan
 
 
二. python 中常用的私有變量
 
####python 中常用的私有變量:
  # __dict__ :類的屬性(包含一個字典,由類的數據屬性組成)
  # __doc__:類的文檔字符串
  # __module__: 定義所在的模塊(類的全名是 '__main_.className',如果類位於一個導入模塊mymod中那么className.__module__ 等於mymod)
  #__bases__ :類的所有父類構成元素(包含由一個所有父類組成的元組)
 
print dir(a)
#['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
# '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
#  '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
# '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
#  '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split',
#  '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode',
# 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha',
# 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
# 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
# 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
#  'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
 
# __doc__ 可以打印出類里的解釋說明
print (a.__doc__)
print (a.__class__)
print (a.__dict__)
 
 
>>>
['_A__sex', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_name', 'get_sex', 'hello']
類的私有變量和私有屬性
<class '__main__.A'>
{}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM