您的位置:首页 > 其它

2020-07-07

2020-07-07 13:54 84 查看

面向对象继承

继承的概念:Java中的继承使用的是extends关键字,继承的类叫做子类,被继承的类叫做父类。凡是这种可以有包含关系的类都能实现继承关系。
继承的作用:减少代码重复率,提高代码复用性

步骤:
1.根据子类是一个父类的逻辑确定父类的名字
2.将子类公共的属性和方法定义在父类中
3.用extends表示父子关系
4.在子类中定义自己特有的属性和方法

class Person:
def __init__(self,name,age):
self.name = name
self.__age = age  #私有属性

def say_age(self):
pass
#print('年龄是{0}'.format(self.age))

class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score

print(Student.mro())  #Student.mro()显示子类的继承结构
s = Student("马宝林",18,80)
s.say_age()
#print(s.age)  #父类里面是私有的,私有方法属性,子类继承了但是不能用
print(s._Person__age)
print(dir(s))
print(s.name)

方法的重写

1.子类可以继承父类方法,但有时从父类继承的方法在子类中必须进行修改以适应新类的需要,这种对父类方法进行改写或改造的现象称为方法重写或方法覆盖。父类方法在子类中重写使继承更加灵活。

2.子类重写了父类的方法,则使用子类创建的对象调用该方法时,调用的是重写后的方法,即子类中的方法

class Person:
def __init__(self,name,age):        self.name = name
self.__age = age  #私有属性    def say_age(self):
print('我的年龄是{0}'.format(self.__age))    def say_introduction(self):
print("我的名字是:{}".format(self.name))class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
def say_introduction(self):
#重写父类的方法
print("报告老师,我的名字是:{}".format(self.name))s = Student("马宝林",18,80)s.say_age()s.say_introduction()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: