ptyhon 子类访问父类私有属性

ahuiok 2020-08-10 12:06:40
子类什么也不写时,可以正常访问

代码如下:

#父类
class School(object):
def __init__(self):
self.money = 1000
self.__money = 200000

def __money_info(self):
print(f'私房钱:[{self.__money}]')

def print_info(self):
self.__money_info()

def get_money(self):
return self.__money

# 子类
class Students(School):
pass


s = Students()
print(s.get_money()) # >>> 200000
s.print_info() # >>> 私房钱:[200000]


可在子类中定义了 __init__后,就报错,求解
改动代码如下:


class Students(School):
def __init__(self):
pass


报错信息:AttributeError: 'Students' object has no attribute '_School__money'
...全文
114 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
庸了个白 2020-08-10
  • 打赏
  • 举报
回复

# 子类
class Students(School):
def __init__(self):
super().__init__()

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧