#继承:继承可以使用其他类当作自己的父类,
#那么父类中的方法和公有属性都可以被子类使用。
#继承的好处是可以让子类节省代码,实现更多的功能。
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print('我在吃饭')
def run(self):
print('我在跑步')
class Student(Person):
pass
p=Student('luobin',18)
p.eat()
p.run()
print(p.name)
print(p.age)
#重写父类的方法:
#1.有些时候,父类中的方法不一定适合子类,
#那么这时候可以重写父类的方法,而使用子类自己定义的方法
#2.有时候想使用父类的方法,但是父类中的方法不完全满足我们的需求,
#那么就可以在子类的同名方法中使用super关键字调用父类的方法,
#然后再在子类中实现自己的需求:
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print('人在吃饭')
class Student(Person):
# 1. 如果父类的方法不能满足子类的需求,那么可以重写这个方法,
# 以后对象调用同名方法的时候,就只会执行子类的这个方法。
# 2. 虽然父类的方法不能完全满足子类的需求,但是父类的方法的代码
# 还是需要执行,那么可以通过super这个函数来调用父类的方法。
# 3. super的用法:super(类名,self).方法名([参数])
def __init__(self,name,age):
super(Student,self).__init__(name,age)
print('学生初始化方法')
def eat(self):
super(Student,self).eat()
print('学生在吃饭')
def greet(self):
print("hello,my name is %s.my age is %d"%(self.name,self.age))
p=Student('luobin',18)
p.eat()
python中面向对象的继承
最新推荐文章于 2024-08-15 01:55:01 发布