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'>
{}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/lzcys8868/p/7797501.html