Python教程

python封装

本文主要是介绍python封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
class person():
    def __init__(self,name):
        self.name=name
    @property
    def a(self):
        return 'i am a person,my name is %s' %self.name
class student(person):
    def __init__(self,name,age):
        super(student,self).__init__(name)
        #self.name=name
        self.age=age

    @property
    def a(self):
        return 'i am a student,my name is %s' %self.name
class teacher(person):
    def __init__(self,name,score):
        super(teacher,self).__init__(name)
        #self.name = name
        self.score=score

    @property
    def a(self):
        return 'i am a teacher,my name is %s'%self.name
def show_a(x):
    print(x.a)

p=person('bob')
s=student('alice',12)
t=teacher('lily',80)

show_a(p)
# #i am a person,my name is bob
show_a(s)
# # i am a student,my name is alice
show_a(t)
# # i am a teacher,my name is lily

遇上一篇多态的区别:使用了property装饰器,print(x.a())改写成print(x.a),即调用函数的时候不需要再加括号

这篇关于python封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!