Python 类的私有成员

本文详细介绍了Python中类的私有成员,包括私有属性、私有对象属性和私有类方法的使用规则及访问限制。通过示例代码展示了如何在类的内部和外部访问私有成员,并解释了如何通过特殊方式来间接访问这些私有成员。
摘要由CSDN通过智能技术生成
# !/usr/bin/env python
# -*- coding:utf-8 -*-


"""
类的私有成员:
    遇到重要数据、功能(只允许本类使用的一些方法、数据),设置成私有成员。
类在加载到内存的时候,只要遇到类中的私有成员,都会在私有成员前面加上 "_类名"。
"""

"""
私有类的属性:
    1、只能在类的内部访问和使用私有类的属性
    2、在类的外部不可以访问和使用私有类的属性
    3、在类的子类(派生类)不可以访问父类的私有类的属性
"""

class Person:
    name = 'albert'
    __age = 17  # 私有类的属性

    def get_info(self):
        print(self.name)
        print(self.__age)


p1 = Person()
p1.get_info()
print(p1.name)
# print(p1.__age)  # 报错,'Person' object has no attribute '__age'
# print(Person.__age)  # 报错, type object 'Person' has no attribute '__age'

# 不过,可以通过特殊方法来访问和使用私有类的属性:
print(Person.__dict__)  # 注意这个:'_Person__age': 17,
print(p1._Person__age)  # 17
print(Person._Person__age)  # 17


"""
私有对象属性:
    1、只能在类的内部访问和使用私有对象属性
    2、在类的外部不可以访问和使用私有对象属性
    3、在类的子类(派生类)也不可以访问父类的私有对象属性
"""


class Student:

    def __init__(self, name, score):
        self.name = name
        self.__score = score  # 私有对象属性

    def get_info(self):
        print(self.name)
        print(self.__score)


stu = Student('don', 97)
stu.get_info()

print(stu.name)
# print(stu.__score) # 报错, 'Student' object has no attribute '__score'

# 不过,可以通过特殊方法来访问和使用私有对象属性:
print(stu.__dict__)  # 注意:{'name': 'don', '_Student__score': 97}
print(stu._Student__score)  # 97


"""
私有类的方法:
    1、只能在类的内部访问和使用私有类的方法
    2、在类的外部不可以访问和使用私有类的方法
    3、在类的子类(派生类)也不可以访问父类的私有类的方法
"""


class Hello:
    def hello(self):
        print('Hello World 01')
        self.__hello()

    def __hello(self):  # 私有类的方法
        print('Hello World 02')

h = Hello()
h.hello()
# h.__hello()  # 报错, 'Hello' object has no attribute '__hello'

# 不过,可以通过特殊方法来访问和使用私有类的方法:
print(Hello.__dict__)  # 注意:'_Hello__hello': <function Hello.__hello at 0x00000112AD596EE0>
print(h._Hello__hello())

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值