基于Inheritan的Python编程

2024-09-28 20:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个代码,其中我有一个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')

现在,我的问题是:如何得到输出年龄


Tags: ofnameselfformatageinitisdef
1条回答
网友
1楼 · 发布于 2024-09-28 20:58:29

您想阅读^{} function文档;你没有按设计的方式使用它;函数根据一个规范(可选的第二个参数)格式化一个值

实际上,您根本不需要使用它

使用^{}代替字符串上的方法:

print 'Name: {}\t Age: {}'.format(self.name, self.age)

这里{}占位符被传递给方法的值替换

注意,我没有使用print作为函数;在python2中,它是一个语句;这就是为什么在执行print()时会看到();那只是print tuple(),真的。您可以在模块的顶部使用from __future__ import print_function,但我现在仍然使用旧的语句;最好完全切换到Python3

接下来,要直接从子类执行重写的SchoolMember.tell()方法:

def tell(self):
    '''Tells the fees of the student'''
    SchoolMember.tell(self)
    print 'Fees  of student is {}'.format(self.fees)

因为您访问类上的方法unbound,所以需要手动传入self

在新样式类中(从python3中的默认基类object继承),也可以使用^{} function;如果您的教程已经在使用super(),但是您无法让它正常工作,那么您很可能正在学习python3教程,并且希望升级,而不是继续使用该语言的旧版本

相关问题 更多 >