我编写了一个代码,其中我有一个SchoolMember
的基类,并派生了两个类:Teacher
&Student
。请参考以下代码:
class SchoolMember:
'''Represents school member'''
def __init__(self,name,age):
self.name=name
self.age=age
print('Initialised school member is:', format(self.name))
def tell(self):
print ('Name: \t Age: ', format(self.name, self.age))
class Teacher(SchoolMember):
def __init__(self,name,salary,age):
SchoolMember.__init__(self,name,age)
self.salary=salary
print ('Initialised teacher is ', format(self.name))
def tell(self):
'''Prints the salary of the teacher'''
print('Salary of teacher is ', format(self.salary))
class Student(SchoolMember):
def __init__(self,name,age,fees):
SchoolMember.__init__(self,name,age)
self.fees=fees
print('Initialised student is',format(self.name))
def tell(self):
'''Tells the fees of the student'''
print('Fees of student is', format(self.fees))
t = Teacher('Richa', 26,4000)
s = Student('Shubh',21, 2000)
print()
members = [t,s]
for member in members:
member.tell()
输出:
('Initialised school member is:', 'Richa')
('Initialised teacher is ', 'Richa')
('Initialised school member is:', 'Shubh')
('Initialised student is', 'Shubh')
()
('Salary of teacher is ', '4000')
('Fees of student is', '2000')
现在,我的问题是:如何得到输出年龄
您想阅读^{} function 文档;你没有按设计的方式使用它;函数根据一个规范(可选的第二个参数)格式化一个值
实际上,您根本不需要使用它
使用^{} 代替字符串上的方法:
这里
{}
占位符被传递给方法的值替换注意,我没有使用
print
作为函数;在python2中,它是一个语句;这就是为什么在执行print()
时会看到()
;那只是print tuple()
,真的。您可以在模块的顶部使用from __future__ import print_function
,但我现在仍然使用旧的语句;最好完全切换到Python3接下来,要直接从子类执行重写的
SchoolMember.tell()
方法:因为您访问类上的方法unbound,所以需要手动传入
self
在新样式类中(从python3中的默认基类} function ;如果您的教程已经在使用
object
继承),也可以使用^{super()
,但是您无法让它正常工作,那么您很可能正在学习python3教程,并且希望升级,而不是继续使用该语言的旧版本相关问题 更多 >
编程相关推荐