该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Author:"BeiMingFish"
#创建一个Person类,根据Person类派生Student类,分别创建Person与Student类的对
import types
#定义Person类
class Person(object):
def __init__(self,name='',age=20,sex='male'):
self.setName(name)
self.setAge(age)
self.setSex(sex)
def setName(self,name):
if type(name) != str:
print('姓名必须是字符串!')
return
self.__name = name
def setAge(self,age):
if type(age) != int:
print('年龄必须是整数!')
return
self.__age = age
def setSex(self,sex):
if sex != 'male' and sex != 'female':
print('输入性别有误!')
return
self.__sex =sex
def show(self):
print('姓名:',self.__name,'年龄:',self.__age,'性别:',self.__sex)
#定义子类Student,增加一个入学年份的私有属性
class Student(Person):
def __init__(self,name='',age=20,sex='male',schoolyear = 2016):
super(Student,self).__init__(name,age,sex)
#Person.__init__(self,name,age,sex)
self.setSchoolyear(schoolyear)
def setSchoolyear(self,schoolyear):
self.__schoolyear = schoolyear
def show(self):
Person.show(self)
#super(Student,self).show()
print('入学年份:',self.__schoolyear)
if __name__ == '__main__':
zhangsan = Person('张三',20,'male')
zhangsan.show()
lisi = Student('李四',24,'male',2017)
lisi.show()
lisi.setAge(21)
lisi.setSchoolyear(2019)
lisi.show()
上面是问题代码,我看不出哪里有问题。
我把基类的show()方法不打印self.__age后,就不会报错了
报错信息:
C:\Python37\python.exe D:/python/S15/ClassPersonAndStudent.py
Traceback (most recent call last):
File "D:/python/S15/ClassPersonAndStudent.py", line 53, in
zhangsan.show()
File "D:/python/S15/ClassPersonAndStudent.py", line 33, in show
print('姓名:',self.__name,'年龄:',self.__age,'性别:',self.__sex)
AttributeError: 'Person' object has no attribute '_Person__age'
父类中删除show()方法中的self.__age后能正常打印:
姓名: 张三 性别: male
姓名: 李四 性别: female
入学年份: 2017
姓名: 李四 性别: female
入学年份: 2019