zoukankan      html  css  js  c++  java
  • 13私有属性和私有方法

    1. 应用场景及定义方式

    应用场景

    • 在实际开发中, 对象 某些属性或方法 可能只希望 在对象的内部被使用, 不希望在外部被访问到
    • 私有属性 就是 对象 不希望公开的 属性
    • 私有方法 就是 对象 不希望公开的 方法

    定义方式

    • 定义属性或方法时, 属性名或者方法名前 增加 两个下划线, 定义的就是 私有 属性或方法
    Women

    name

    __age

    __init__(self, name):

    __secret(self):

     1 class Women:
     2 
     3     def __init__(self, name):
     4 
     5         self.name = name
     6         self.__age = 18
     7 
     8     def __secret(self):
     9         # 在对象的方法内部, 是可以访问对象的私有属性的
    10         print("%s 的年龄是 %d" % (self.name, self.__age))
    11 
    12     def tell(self):
    13         # 在对象的方法内部, 是可以访问对象的方法
    14         self.__secret()
    15 
    16 
    17 xiaofang = Women("小芳")
    18 
    19 # 私有属性, 在外界不能够直接访问
    20 # print(xiaofang.age)
    21 # 私有方法, 同样不允许在外界直接访问
    22 # print(xiaofang.__secret())
    23 xiaofang.tell()

    2. 伪私有属性和私有方法(科普不推荐使用)

    提示 : 在日常开发中, 不要使用这种方法, 访问对象的 私有属性 或 私有方法

    Python 中, 并没有 真正意义私有

    • 再给 属性, 方法 命名时, 实际是对 名称 做了一些特殊处理, 使得外界无法访问到
    • 处理方式: 名称 前面加上 _类名 => _类名__名称
    1 # 私有属性 这样访问
    2 print(xiaofang._Women__age)
    3 # 私有属性 这样访问
    4 print(xiaofang._Women__secret())
  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/xinmomoyan/p/10347157.html
Copyright © 2011-2022 走看看