本文会用到以下文章的Date类:Python中的静态方法、类方法以及对象方法(实例方法)
class Date:
# 构造函数
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return "{year}/{month}/{day}".format(year = self.year, month = self.month,day = self.day)
定义一个类:
class User:
def __init__(self, birthday):
self.birthday = birthday
def get_age(self):
# 返回年龄
return 2020 - self.birthday.year
if __name__ == "__main__":
user = User(Date(1990, 2, 1))
print(user.get_age())
运行一下:

现在是直接可以访问user的生日的:

如果希望将User的出生日期隐藏,不希望直接可以访问,可以在birthday前面加两个下划线表示私有属性:
class User:
def __init__(self, birthday):
self.__birthday = birthday
def get_age(self):
# 返回年龄
return 2020 - self.__birthday.year
这时候再来访问user的生日的,就访问不到了:

子类也无法获取这个birthday。
在加上双下划线之后,Python把这个变量的格式变化成了如下格式:
_classname__attr
。也就是把
__birthday
变为了_User__birthday
,使用这个格式再来print一下:
注意类名(classname)是
User
而不是user
。所以还是可以访问得到。
网友评论