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
  • 相关阅读:
    php foreach的使用注意
    php数组遍历 使用foreach
    PHP strip_tags() 函数
    php nl2br() 函数
    php文件上传
    一个网站雏形
    jsp接收相同复合参数 request.getParameterValues()用法
    使用div+css制作简单导航 以及要注意问题
    Java 类与对象
    java 基础
  • 原文地址:https://www.cnblogs.com/chushujin/p/13071462.html
Copyright © 2011-2022 走看看