数据封装和私有属性

本文介绍了Python中私有属性的概念,以及名称修饰(name mangling)机制的作用,旨在防止子类意外覆盖父类的私有属性,避免命名冲突。通过实例展示了Python如何自动修改双下划线开头的属性名,以保护父类实现不受子类影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import time

class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return f"{self.year}/{self.month}/{self.day}"

class User:
    def __init__(self, birthday):
        self.__birthday = birthday    # self.__birthday  <==> self._User__birthday

    def get_age(self):
        return time.localtime().tm_year - self.__birthday.year

class Student(User):

    def __init__(self, birthday):
        super().__init__(birthday)
        self.__birthday = birthday  # self.__birthday  <==> self._Student__birthday

user = User(Date(1995, 12, 12))
print(user.get_age())
print(user._User__birthday)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值