zoukankan      html  css  js  c++  java
  • Python3-2020-测试开发-19- Python中私有属性和私有方法

    私有属性和私有方法

    """私有属性-私有方法,实现封装
    1. 通畅我们约定,两个下划线开头的属性是私有属性(private),其他的都为公共的(public)
    2. 类内部可以访问私有属性(方法)
    3. 类外部不能直接访问私有属性(方法)
    4. 类外部可以通过“_类名__私有属性(方法)名”访问私有属性(方法)
    
    """

    代码举例:

    class Employee:
    
        __company = "BYD"
    
        def __init__(self,name,age):
    
            self.name = name
            self.__age = age                # 私有属性
    
        def __work(self):                   # 私有方法
    
            print("好好工作")
            print("年龄为:{0}".format(self.__age))
            print("公司名称为:{0}".format(Employee.__company))
    
    
    
    e = Employee("chu01",18)
    print(e.name)        # chu01
    
    print(dir(e))
    """
    ['_Employee__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
    '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
    '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
    '__setattr__','__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
    """
    # print(e.age)     # AttributeError: 'Employee' object has no attribute 'age'
    
    # 私有属性访问
    print(e._Employee__age)      # 18
    
    # 私有方法访问
    e._Employee__work()          # 好好工作  年龄为:18    公司名称为:BYD
    
    # 私有属性访问
    print(Employee._Employee__company)     # BYD
  • 相关阅读:
    7-1 N个数求和
    3662. 最大上升子序列和
    树状数组
    堆优化Dijkstra java模板
    皮亚诺曲线距离
    最长公共子序列(计数问题)
    最小路径覆盖
    极角排序
    2619. 询问
    Hessian矩阵与局部极小值
  • 原文地址:https://www.cnblogs.com/chushujin/p/13071462.html
Copyright © 2011-2022 走看看