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)
stu = Student(Date(1997, 8, 4))
print(stu.get_ag
数据封装和私有属性
最新推荐文章于 2025-10-23 15:19:07 发布
本文介绍了Python中私有属性的概念,以及名称修饰(name mangling)机制的作用,旨在防止子类意外覆盖父类的私有属性,避免命名冲突。通过实例展示了Python如何自动修改双下划线开头的属性名,以保护父类实现不受子类影响。
订阅专栏 解锁全文
11万+

被折叠的 条评论
为什么被折叠?



